pi-fabric 0.127.1 → 0.128.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.md +0 -7
  3. package/dist/agents/provider-bridge.d.ts +2 -2
  4. package/dist/agents/provider-bridge.js.map +1 -1
  5. package/dist/chunks/{chunk-OWR32LJF.js → chunk-SWTFJEPN.js} +282 -111
  6. package/dist/chunks/chunk-SWTFJEPN.js.map +7 -0
  7. package/dist/core/program-tasks.d.ts +52 -0
  8. package/dist/core/program-tasks.d.ts.map +1 -0
  9. package/dist/core/shell-inbox.d.ts.map +1 -1
  10. package/dist/core/shell-jobs.d.ts +7 -5
  11. package/dist/core/shell-jobs.d.ts.map +1 -1
  12. package/dist/core/shell-timing.d.ts.map +1 -1
  13. package/dist/extension-bootstrap.js +1 -1
  14. package/dist/extension.d.ts.map +1 -1
  15. package/dist/fabric-exec-arguments.d.ts.map +1 -1
  16. package/dist/fabric-exec-tool.d.ts.map +1 -1
  17. package/dist/fabric-runtime-state.js +17 -6
  18. package/dist/fabric-runtime-state.js.map +2 -2
  19. package/dist/fabric-state.d.ts +3 -0
  20. package/dist/fabric-state.d.ts.map +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/ui/shell-hang-keys.d.ts +8 -1
  23. package/dist/ui/shell-hang-keys.d.ts.map +1 -1
  24. package/docs/agents.md +1 -1
  25. package/docs/background-tasks.md +31 -0
  26. package/docs/codemode-parity.md +1 -1
  27. package/docs/configuration.md +8 -47
  28. package/docs/managed-host-migration.md +12 -12
  29. package/docs/skills.md +1 -1
  30. package/package.json +2 -7
  31. package/skillsets/python/fabric-exec/references/agents.md +2 -0
  32. package/skillsets/typescript/fabric-exec/references/agents.md +2 -0
  33. package/dist/chunks/chunk-OWR32LJF.js.map +0 -7
  34. package/node_modules/pi-coralbricks-provider/LICENSE +0 -21
  35. package/node_modules/pi-coralbricks-provider/README.md +0 -306
  36. package/node_modules/pi-coralbricks-provider/auth.ts +0 -30
  37. package/node_modules/pi-coralbricks-provider/custom-models.json +0 -1
  38. package/node_modules/pi-coralbricks-provider/deprecated-models.json +0 -1
  39. package/node_modules/pi-coralbricks-provider/guard.ts +0 -155
  40. package/node_modules/pi-coralbricks-provider/index.ts +0 -662
  41. package/node_modules/pi-coralbricks-provider/models.json +0 -88
  42. package/node_modules/pi-coralbricks-provider/package.json +0 -74
  43. package/node_modules/pi-coralbricks-provider/park.ts +0 -122
  44. package/node_modules/pi-coralbricks-provider/patch.json +0 -34
  45. package/node_modules/pi-coralbricks-provider/scripts/update-models.js +0 -658
  46. package/node_modules/pi-coralbricks-provider/settings.ts +0 -143
  47. package/node_modules/pi-coralbricks-provider/sync-policy.ts +0 -309
package/README.md CHANGED
@@ -96,7 +96,7 @@ Requires Node.js 24+ and Pi 1.0.0+. Monty's optional native package installs on
96
96
  pi install npm:pi-fabric
97
97
  ```
98
98
 
99
- Fabric bundles the [Coral Bricks provider](docs/configuration.md#bundled-coral-bricks-provider): run `/login coralbricks` to use `coralbricks/*` models, or opt out with a package filter. Fabric's maintainers work at Coral Bricks.
99
+ Fabric does not bundle third-party chat model provider extensions. Install third-party providers separately; see [provider configuration](docs/configuration.md#third-party-model-providers).
100
100
 
101
101
  <details>
102
102
  <summary>Other install methods</summary>
@@ -8,13 +8,6 @@ Haydn Paterson, licensed under MIT. This private artifact is not loaded by the
8
8
  Pi extension, which continues to use Pi's host-provided TypeBox. The complete
9
9
  license is distributed at [docs/licenses/typebox-mit.txt](docs/licenses/typebox-mit.txt).
10
10
 
11
- ## pi-coralbricks-provider
12
-
13
- The package bundles [`pi-coralbricks-provider`](https://github.com/monotykamary/pi-coralbricks-provider)
14
- unmodified under `node_modules/pi-coralbricks-provider`, at the exact version
15
- pinned in `package.json`. It is licensed under MIT, and its complete license is
16
- distributed beside it at `node_modules/pi-coralbricks-provider/LICENSE`.
17
-
18
11
  ## gdp-wired
19
12
 
20
13
  The generated verified kernels in `dist/verified/generated/` are JavaScript
@@ -40,8 +40,8 @@ export declare function orderProviderCandidates(paths: readonly string[], provid
40
40
  };
41
41
  /**
42
42
  * Fabric's own manifest entries: they never register chat providers. Entries
43
- * of bundled Pi packages (pi-coralbricks-provider) are not Fabric's own: they
44
- * stay probe candidates, so the bundled provider resolves without loading
43
+ * of bundled Pi packages are not Fabric's own: they stay probe candidates,
44
+ * so a bundled provider can resolve without loading
45
45
  * Fabric's main extension.
46
46
  */
47
47
  export declare function fabricExtensionEntries(moduleUrl?: string): string[];
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/agents/provider-bridge.ts"],
4
- "sourcesContent": ["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Provider } from \"@earendil-works/pi-ai\";\nimport type { ExtensionAPI, ProviderConfig, SettingsManager } from \"@earendil-works/pi-coding-agent\";\nimport { loadHostSdk } from \"../core/host-sdk.js\";\n\n/**\n * The `provider/id` key a Pi child launched with `extensions: false` must\n * resolve. The worker sets it only when it also loads this bridge with `-e`.\n */\nexport const PROVIDER_BRIDGE_MODEL_ENV = \"PI_FABRIC_EXTENSION_MODEL\";\n\nexport interface ExtensionProviderRegistrations {\n configs: Array<{ name: string; config: ProviderConfig; extensionPath: string }>;\n natives: Array<{ provider: Provider; extensionPath: string }>;\n}\n\nexport interface ResolveExtensionProvidersOptions {\n model: string;\n cwd: string;\n agentDir: string;\n /** Extension entry files never probed (Fabric's own entries by default). */\n exclude?: readonly string[];\n}\n\ntype PiSdk = typeof import(\"@earendil-works/pi-coding-agent\");\n\n/** Split a canonical `provider/id` key at its first slash. */\nexport function parseModelKey(key: string): { provider: string; id: string } | undefined {\n const value = key.trim();\n const slash = value.indexOf(\"/\");\n if (slash <= 0 || slash === value.length - 1) return undefined;\n return { provider: value.slice(0, slash), id: value.slice(slash + 1) };\n}\n\n/**\n * Probe extensions whose own path names the provider first (the usual\n * `pi-<provider>-provider` package), so the common case runs one registration\n * function instead of every installed extension.\n */\nexport function orderProviderCandidates(\n paths: readonly string[],\n provider: string,\n): { named: string[]; rest: string[] } {\n const needle = provider.toLowerCase();\n const named: string[] = [];\n const rest: string[] = [];\n for (const candidate of paths) {\n const tail = candidate.split(/[\\\\/]+/).filter(Boolean).slice(-3);\n (tail.some((segment) => segment.toLowerCase().includes(needle)) ? named : rest).push(candidate);\n }\n return { named, rest };\n}\n\nconst realPath = (file: string): string => {\n try {\n return fs.realpathSync(file);\n } catch {\n return path.resolve(file);\n }\n};\n\n/** A manifest entry that loads a Pi package Fabric bundles (`node_modules/<package>/...`). */\nconst isBundledPackageEntry = (entry: string): boolean =>\n entry.replace(/\\\\/g, \"/\").replace(/^(?:\\.\\/)+/, \"\").startsWith(\"node_modules/\");\n\n/**\n * Fabric's own manifest entries: they never register chat providers. Entries\n * of bundled Pi packages (pi-coralbricks-provider) are not Fabric's own: they\n * stay probe candidates, so the bundled provider resolves without loading\n * Fabric's main extension.\n */\nexport function fabricExtensionEntries(moduleUrl = import.meta.url): string[] {\n const root = path.resolve(path.dirname(fileURLToPath(moduleUrl)), \"..\", \"..\");\n try {\n const manifest = JSON.parse(fs.readFileSync(path.join(root, \"package.json\"), \"utf8\")) as {\n name?: unknown;\n main?: unknown;\n pi?: { extensions?: unknown };\n };\n if (manifest.name !== \"pi-fabric\") return [];\n const entries = [manifest.main, ...(Array.isArray(manifest.pi?.extensions) ? manifest.pi.extensions : [])];\n return entries\n .filter((entry): entry is string => typeof entry === \"string\" && !isBundledPackageEntry(entry))\n .map((entry) => path.resolve(root, entry));\n } catch {\n return [];\n }\n}\n\nconst emptyRegistrations = (): ExtensionProviderRegistrations => ({ configs: [], natives: [] });\n\n/**\n * Load extension paths with Pi's own loader into an isolated runtime and keep\n * only the requested provider's registrations. The loaded extensions are\n * discarded: their tools, commands, flags, shortcuts, renderers, and event\n * handlers never bind to the child session, and their event bus is private.\n */\nasync function loadProviderRegistrations(\n sdk: PiSdk,\n paths: readonly string[],\n provider: string,\n options: { cwd: string; agentDir: string; settingsManager: SettingsManager },\n failures: string[],\n): Promise<ExtensionProviderRegistrations> {\n if (paths.length === 0) return emptyRegistrations();\n const loader = new sdk.DefaultResourceLoader({\n cwd: options.cwd,\n agentDir: options.agentDir,\n settingsManager: options.settingsManager,\n noExtensions: true,\n additionalExtensionPaths: [...paths],\n noSkills: true,\n noPromptTemplates: true,\n noThemes: true,\n noContextFiles: true,\n });\n await loader.reload();\n const { runtime, errors } = loader.getExtensions();\n failures.push(...errors.map((error) => error.path));\n return {\n configs: runtime.pendingProviderRegistrations\n .filter((registration) => registration.name === provider)\n .map(({ name, config, extensionPath }) => ({ name, config, extensionPath })),\n natives: runtime.pendingNativeProviderRegistrations\n .filter((registration) => registration.provider.id === provider)\n .map(({ provider: registered, extensionPath }) => ({ provider: registered, extensionPath })),\n };\n}\n\n/**\n * Find the extension registrations that make `model` resolvable in a child\n * without its other extensions. Returns `undefined` when Pi already knows the\n * model (built in, models.json, or a cached catalog), so those children keep\n * their exact extension-free behaviour. Throws an actionable error when no\n * installed extension registers the provider.\n */\nexport async function resolveExtensionProviders(\n options: ResolveExtensionProvidersOptions,\n sdk?: PiSdk,\n): Promise<ExtensionProviderRegistrations | undefined> {\n const key = parseModelKey(options.model);\n if (!key) return undefined;\n const pi = sdk ?? await loadHostSdk();\n const models = await pi.ModelRuntime.create({\n authPath: path.join(options.agentDir, \"auth.json\"),\n modelsPath: path.join(options.agentDir, \"models.json\"),\n refreshOnCreate: false,\n });\n if (models.getModel(key.provider, key.id)) return undefined;\n await models.refresh({ allowNetwork: false, signal: AbortSignal.timeout(15_000) });\n if (models.getModel(key.provider, key.id)) return undefined;\n\n // Same trust a headless child applies without consulting extension\n // project_trust handlers: those belong to the extensions left out here.\n const untrusted = pi.SettingsManager.create(options.cwd, options.agentDir, { projectTrusted: false });\n const trusted = !pi.hasTrustRequiringProjectResources(options.cwd) ||\n (new pi.ProjectTrustStore(options.agentDir).get(options.cwd) ?? untrusted.getDefaultProjectTrust() === \"always\");\n const settingsManager = trusted\n ? pi.SettingsManager.create(options.cwd, options.agentDir, { projectTrusted: true })\n : untrusted;\n const resolved = await new pi.DefaultPackageManager({\n cwd: options.cwd,\n agentDir: options.agentDir,\n settingsManager,\n }).resolve();\n const excluded = new Set((options.exclude ?? fabricExtensionEntries()).map(realPath));\n const candidates = resolved.extensions\n .filter((resource) => resource.enabled && !resource.path.startsWith(\"builtin:\"))\n .map((resource) => resource.path)\n .filter((candidate) => !excluded.has(realPath(candidate)));\n const { named, rest } = orderProviderCandidates(candidates, key.provider);\n const context = { cwd: options.cwd, agentDir: options.agentDir, settingsManager };\n const failures: string[] = [];\n for (const group of [named, rest]) {\n const found = await loadProviderRegistrations(pi, group, key.provider, context, failures);\n if (found.configs.length > 0 || found.natives.length > 0) return found;\n }\n throw new Error(\n `Model \"${options.model}\" needs provider \"${key.provider}\", which is not built into Pi or defined in models.json, ` +\n \"and no installed Pi extension registers it for this extensions: false child. \" +\n \"Install the extension that provides it, or run the child with extensions: true.\" +\n (failures.length > 0 ? ` Extensions that failed to load while searching: ${[...new Set(failures)].join(\", \")}.` : \"\"),\n );\n}\n\n/**\n * Loaded with `-e` into Pi children launched with `extensions: false`. It\n * registers only the requested model's provider, as its extension registered\n * it, so credentials still resolve in the child through auth.json, the\n * environment, or the credential store. Nothing else from that extension loads.\n */\nexport default async function fabricProviderBridge(pi: ExtensionAPI): Promise<void> {\n const model = process.env[PROVIDER_BRIDGE_MODEL_ENV]?.trim();\n if (!model) return;\n const sdk = await loadHostSdk();\n const found = await resolveExtensionProviders({ model, cwd: process.cwd(), agentDir: sdk.getAgentDir() }, sdk);\n if (!found) return;\n for (const { name, config } of found.configs) pi.registerProvider(name, config);\n for (const { provider } of found.natives) pi.registerProvider(provider);\n}\n"],
4
+ "sourcesContent": ["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Provider } from \"@earendil-works/pi-ai\";\nimport type { ExtensionAPI, ProviderConfig, SettingsManager } from \"@earendil-works/pi-coding-agent\";\nimport { loadHostSdk } from \"../core/host-sdk.js\";\n\n/**\n * The `provider/id` key a Pi child launched with `extensions: false` must\n * resolve. The worker sets it only when it also loads this bridge with `-e`.\n */\nexport const PROVIDER_BRIDGE_MODEL_ENV = \"PI_FABRIC_EXTENSION_MODEL\";\n\nexport interface ExtensionProviderRegistrations {\n configs: Array<{ name: string; config: ProviderConfig; extensionPath: string }>;\n natives: Array<{ provider: Provider; extensionPath: string }>;\n}\n\nexport interface ResolveExtensionProvidersOptions {\n model: string;\n cwd: string;\n agentDir: string;\n /** Extension entry files never probed (Fabric's own entries by default). */\n exclude?: readonly string[];\n}\n\ntype PiSdk = typeof import(\"@earendil-works/pi-coding-agent\");\n\n/** Split a canonical `provider/id` key at its first slash. */\nexport function parseModelKey(key: string): { provider: string; id: string } | undefined {\n const value = key.trim();\n const slash = value.indexOf(\"/\");\n if (slash <= 0 || slash === value.length - 1) return undefined;\n return { provider: value.slice(0, slash), id: value.slice(slash + 1) };\n}\n\n/**\n * Probe extensions whose own path names the provider first (the usual\n * `pi-<provider>-provider` package), so the common case runs one registration\n * function instead of every installed extension.\n */\nexport function orderProviderCandidates(\n paths: readonly string[],\n provider: string,\n): { named: string[]; rest: string[] } {\n const needle = provider.toLowerCase();\n const named: string[] = [];\n const rest: string[] = [];\n for (const candidate of paths) {\n const tail = candidate.split(/[\\\\/]+/).filter(Boolean).slice(-3);\n (tail.some((segment) => segment.toLowerCase().includes(needle)) ? named : rest).push(candidate);\n }\n return { named, rest };\n}\n\nconst realPath = (file: string): string => {\n try {\n return fs.realpathSync(file);\n } catch {\n return path.resolve(file);\n }\n};\n\n/** A manifest entry that loads a Pi package Fabric bundles (`node_modules/<package>/...`). */\nconst isBundledPackageEntry = (entry: string): boolean =>\n entry.replace(/\\\\/g, \"/\").replace(/^(?:\\.\\/)+/, \"\").startsWith(\"node_modules/\");\n\n/**\n * Fabric's own manifest entries: they never register chat providers. Entries\n * of bundled Pi packages are not Fabric's own: they stay probe candidates,\n * so a bundled provider can resolve without loading\n * Fabric's main extension.\n */\nexport function fabricExtensionEntries(moduleUrl = import.meta.url): string[] {\n const root = path.resolve(path.dirname(fileURLToPath(moduleUrl)), \"..\", \"..\");\n try {\n const manifest = JSON.parse(fs.readFileSync(path.join(root, \"package.json\"), \"utf8\")) as {\n name?: unknown;\n main?: unknown;\n pi?: { extensions?: unknown };\n };\n if (manifest.name !== \"pi-fabric\") return [];\n const entries = [manifest.main, ...(Array.isArray(manifest.pi?.extensions) ? manifest.pi.extensions : [])];\n return entries\n .filter((entry): entry is string => typeof entry === \"string\" && !isBundledPackageEntry(entry))\n .map((entry) => path.resolve(root, entry));\n } catch {\n return [];\n }\n}\n\nconst emptyRegistrations = (): ExtensionProviderRegistrations => ({ configs: [], natives: [] });\n\n/**\n * Load extension paths with Pi's own loader into an isolated runtime and keep\n * only the requested provider's registrations. The loaded extensions are\n * discarded: their tools, commands, flags, shortcuts, renderers, and event\n * handlers never bind to the child session, and their event bus is private.\n */\nasync function loadProviderRegistrations(\n sdk: PiSdk,\n paths: readonly string[],\n provider: string,\n options: { cwd: string; agentDir: string; settingsManager: SettingsManager },\n failures: string[],\n): Promise<ExtensionProviderRegistrations> {\n if (paths.length === 0) return emptyRegistrations();\n const loader = new sdk.DefaultResourceLoader({\n cwd: options.cwd,\n agentDir: options.agentDir,\n settingsManager: options.settingsManager,\n noExtensions: true,\n additionalExtensionPaths: [...paths],\n noSkills: true,\n noPromptTemplates: true,\n noThemes: true,\n noContextFiles: true,\n });\n await loader.reload();\n const { runtime, errors } = loader.getExtensions();\n failures.push(...errors.map((error) => error.path));\n return {\n configs: runtime.pendingProviderRegistrations\n .filter((registration) => registration.name === provider)\n .map(({ name, config, extensionPath }) => ({ name, config, extensionPath })),\n natives: runtime.pendingNativeProviderRegistrations\n .filter((registration) => registration.provider.id === provider)\n .map(({ provider: registered, extensionPath }) => ({ provider: registered, extensionPath })),\n };\n}\n\n/**\n * Find the extension registrations that make `model` resolvable in a child\n * without its other extensions. Returns `undefined` when Pi already knows the\n * model (built in, models.json, or a cached catalog), so those children keep\n * their exact extension-free behaviour. Throws an actionable error when no\n * installed extension registers the provider.\n */\nexport async function resolveExtensionProviders(\n options: ResolveExtensionProvidersOptions,\n sdk?: PiSdk,\n): Promise<ExtensionProviderRegistrations | undefined> {\n const key = parseModelKey(options.model);\n if (!key) return undefined;\n const pi = sdk ?? await loadHostSdk();\n const models = await pi.ModelRuntime.create({\n authPath: path.join(options.agentDir, \"auth.json\"),\n modelsPath: path.join(options.agentDir, \"models.json\"),\n refreshOnCreate: false,\n });\n if (models.getModel(key.provider, key.id)) return undefined;\n await models.refresh({ allowNetwork: false, signal: AbortSignal.timeout(15_000) });\n if (models.getModel(key.provider, key.id)) return undefined;\n\n // Same trust a headless child applies without consulting extension\n // project_trust handlers: those belong to the extensions left out here.\n const untrusted = pi.SettingsManager.create(options.cwd, options.agentDir, { projectTrusted: false });\n const trusted = !pi.hasTrustRequiringProjectResources(options.cwd) ||\n (new pi.ProjectTrustStore(options.agentDir).get(options.cwd) ?? untrusted.getDefaultProjectTrust() === \"always\");\n const settingsManager = trusted\n ? pi.SettingsManager.create(options.cwd, options.agentDir, { projectTrusted: true })\n : untrusted;\n const resolved = await new pi.DefaultPackageManager({\n cwd: options.cwd,\n agentDir: options.agentDir,\n settingsManager,\n }).resolve();\n const excluded = new Set((options.exclude ?? fabricExtensionEntries()).map(realPath));\n const candidates = resolved.extensions\n .filter((resource) => resource.enabled && !resource.path.startsWith(\"builtin:\"))\n .map((resource) => resource.path)\n .filter((candidate) => !excluded.has(realPath(candidate)));\n const { named, rest } = orderProviderCandidates(candidates, key.provider);\n const context = { cwd: options.cwd, agentDir: options.agentDir, settingsManager };\n const failures: string[] = [];\n for (const group of [named, rest]) {\n const found = await loadProviderRegistrations(pi, group, key.provider, context, failures);\n if (found.configs.length > 0 || found.natives.length > 0) return found;\n }\n throw new Error(\n `Model \"${options.model}\" needs provider \"${key.provider}\", which is not built into Pi or defined in models.json, ` +\n \"and no installed Pi extension registers it for this extensions: false child. \" +\n \"Install the extension that provides it, or run the child with extensions: true.\" +\n (failures.length > 0 ? ` Extensions that failed to load while searching: ${[...new Set(failures)].join(\", \")}.` : \"\"),\n );\n}\n\n/**\n * Loaded with `-e` into Pi children launched with `extensions: false`. It\n * registers only the requested model's provider, as its extension registered\n * it, so credentials still resolve in the child through auth.json, the\n * environment, or the credential store. Nothing else from that extension loads.\n */\nexport default async function fabricProviderBridge(pi: ExtensionAPI): Promise<void> {\n const model = process.env[PROVIDER_BRIDGE_MODEL_ENV]?.trim();\n if (!model) return;\n const sdk = await loadHostSdk();\n const found = await resolveExtensionProviders({ model, cwd: process.cwd(), agentDir: sdk.getAgentDir() }, sdk);\n if (!found) return;\n for (const { name, config } of found.configs) pi.registerProvider(name, config);\n for (const { provider } of found.natives) pi.registerProvider(provider);\n}\n"],
5
5
  "mappings": ";;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,qBAAqB;AASvB,IAAM,4BAA4B;AAkBlC,SAAS,cAAc,KAA2D;AACvF,QAAM,QAAQ,IAAI,KAAK;AACvB,QAAM,QAAQ,MAAM,QAAQ,GAAG;AAC/B,MAAI,SAAS,KAAK,UAAU,MAAM,SAAS,EAAG,QAAO;AACrD,SAAO,EAAE,UAAU,MAAM,MAAM,GAAG,KAAK,GAAG,IAAI,MAAM,MAAM,QAAQ,CAAC,EAAE;AACvE;AAOO,SAAS,wBACd,OACA,UACqC;AACrC,QAAM,SAAS,SAAS,YAAY;AACpC,QAAM,QAAkB,CAAC;AACzB,QAAM,OAAiB,CAAC;AACxB,aAAW,aAAa,OAAO;AAC7B,UAAM,OAAO,UAAU,MAAM,QAAQ,EAAE,OAAO,OAAO,EAAE,MAAM,EAAE;AAC/D,KAAC,KAAK,KAAK,CAAC,YAAY,QAAQ,YAAY,EAAE,SAAS,MAAM,CAAC,IAAI,QAAQ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Z,QAAM,MAAM,MAAM,YAAY;AAC9B,QAAM,QAAQ,MAAM,0BAA0B,EAAE,OAAO,KAAK,QAAQ,IAAI,GAAG,UAAU,IAAI,YAAY,EAAE,GAAG,GAAG;AAC7G,MAAI,CAAC,MAAO;AACZ,aAAW,EAAE,MAAM,OAAO,KAAK,MAAM,QAAS,IAAG,iBAAiB,MAAM,MAAM;AAC9E,aAAW,EAAE,SAAS,KAAK,MAAM,QAAS,IAAG,iBAAiB,QAAQ;AACxE;",
6
6
  "names": []
7
7
  }
@@ -1572,7 +1572,8 @@ var OPTIONAL_FABRIC_EXEC_KEYS = [
1572
1572
  "timeout_ms",
1573
1573
  "maxOutputTokens",
1574
1574
  "max_output_tokens",
1575
- "display"
1575
+ "display",
1576
+ "background"
1576
1577
  ];
1577
1578
  var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1578
1579
  var looksLikeJsonObject = (text) => text.startsWith("{") && text.endsWith("}");
@@ -1827,6 +1828,8 @@ var compactResultHeader = (theme, audits, failed) => {
1827
1828
  );
1828
1829
  };
1829
1830
  var countLabel = (count, singular) => `${count} ${count === 1 ? singular : `${singular}s`}`;
1831
+ var FABRIC_DETACHED_OUTPUT_CHARS = 6e3;
1832
+ var fabricDetachedText = (taskId, elapsedMs, requested) => `[fabric_exec ${requested ? "started in the background" : `moved to the background by the user after ${Math.max(1, Math.round(elapsedMs / 1e3))}s`} as task ${taskId}. It keeps running with its tools, child agents, and approvals; its result arrives automatically as a background task event when it finishes. Continue independent work, or end this turn if you need the result. Do not start the same program again. The user can now steer you while it runs. Inspect with tools.call({ref:'tasks.get',args:{id}}); stop with tasks.stop. Its child agents stay steerable with agents.steer.]`;
1830
1833
  var createFabricExecTool = (state, codePreviewSettings, pendingHandoffs, decorateShell = withCodePreviewShell, toolDisplay, terminalTitle) => {
1831
1834
  const managedHost = state.managedHostOptions;
1832
1835
  const python = toolKernel(state) === "python";
@@ -1904,6 +1907,9 @@ var createFabricExecTool = (state, codePreviewSettings, pendingHandoffs, decorat
1904
1907
  description: "Optional whole-program deadline in ms for this invocation; raises (never lowers) the configured executor.timeoutMs, capped by executor.maxTimeoutMs"
1905
1908
  })
1906
1909
  ),
1910
+ background: Type.Optional(Type.Boolean({
1911
+ description: "Run the program as a background task and return at once; its result arrives as a background task event. Use for long workflows (many agents) whose result you do not need before continuing."
1912
+ })),
1907
1913
  timeout_ms: Type.Optional(Type.Integer({ minimum: 1, description: "Hard whole-script deadline in milliseconds; cannot be extended or paused, capped by executor.maxTimeoutMs." })),
1908
1914
  maxOutputTokens: Type.Optional(Type.Integer({ minimum: 1, description: "Per-call output token budget (estimated at four characters per token), capped by executor.maxOutputChars." })),
1909
1915
  max_output_tokens: Type.Optional(Type.Integer({ minimum: 1, description: "Alias of maxOutputTokens." })),
@@ -2437,10 +2443,18 @@ ${preview}` : ""}${hiddenHint}`,
2437
2443
  const runDisplay = normalizeRunDisplay(params.display);
2438
2444
  const tokenBudget = "tokenBudget" in params && typeof params.tokenBudget === "number" ? params.tokenBudget : void 0;
2439
2445
  terminalTitle?.show(context, runDisplay?.name);
2440
- const result = await state.execution.execute({
2446
+ const program = state.programTasks?.begin({
2447
+ code,
2448
+ ...runDisplay?.name ? { description: runDisplay.name } : {},
2449
+ cwd: context.cwd,
2450
+ ...signal ? { parentSignal: signal } : {},
2451
+ jobs: () => state.shellJobs
2452
+ });
2453
+ if (params.background === true) program?.detach();
2454
+ const execution = state.execution.execute({
2441
2455
  code,
2442
2456
  ...strings ? { strings } : {},
2443
- signal,
2457
+ signal: program?.signal ?? signal,
2444
2458
  parentToolCallId: toolCallId,
2445
2459
  context,
2446
2460
  ...tokenBudget !== void 0 ? { tokenBudget } : {},
@@ -2454,6 +2468,8 @@ ${preview}` : ""}${hiddenHint}`,
2454
2468
  }
2455
2469
  } : {},
2456
2470
  onPartial(snapshot) {
2471
+ program?.progress(snapshot.progress);
2472
+ if (program?.job) return;
2457
2473
  onUpdate?.({
2458
2474
  content: [{ type: "text", text: snapshot.progress ?? "" }],
2459
2475
  details: {
@@ -2464,122 +2480,147 @@ ${preview}` : ""}${hiddenHint}`,
2464
2480
  });
2465
2481
  }
2466
2482
  });
2467
- const selectedResultFormat = params.resultFormat ?? state.config.executor.resultFormat;
2468
- const boundarySessionId = context.sessionManager.getSessionId();
2469
- const pendingHandoff = await state.claimHandoff(
2470
- result,
2471
- boundarySessionId,
2472
- selectedResultFormat,
2473
- toolCallId
2474
- );
2475
- if (pendingHandoff) {
2476
- pendingHandoffs.set(toolCallId, pendingHandoff);
2477
- context.ui.setStatus(
2478
- "fabric-prewalk",
2479
- `waiting for fabric_exec boundary \u2192 ${String(pendingHandoff.args.model ?? "executor")}`
2483
+ const finishExecution = async (result, detached) => {
2484
+ const selectedResultFormat = params.resultFormat ?? state.config.executor.resultFormat;
2485
+ const boundarySessionId = context.sessionManager.getSessionId();
2486
+ const pendingHandoff = detached ? void 0 : await state.claimHandoff(
2487
+ result,
2488
+ boundarySessionId,
2489
+ selectedResultFormat,
2490
+ toolCallId
2480
2491
  );
2481
- if (pendingHandoff.readiness?.kind === "unplanned") {
2482
- context.ui.notify(
2483
- `Prewalk: handing off without a recorded plan after ${pendingHandoff.readiness.prompts} reminders.`,
2484
- "warning"
2492
+ if (pendingHandoff) {
2493
+ pendingHandoffs.set(toolCallId, pendingHandoff);
2494
+ context.ui.setStatus(
2495
+ "fabric-prewalk",
2496
+ `waiting for fabric_exec boundary \u2192 ${String(pendingHandoff.args.model ?? "executor")}`
2497
+ );
2498
+ if (pendingHandoff.readiness?.kind === "unplanned") {
2499
+ context.ui.notify(
2500
+ `Prewalk: handing off without a recorded plan after ${pendingHandoff.readiness.prompts} reminders.`,
2501
+ "warning"
2502
+ );
2503
+ }
2504
+ } else if (!detached && state.prewalk.planRequired(boundarySessionId)) {
2505
+ const prewalkStatus = state.prewalk.status();
2506
+ context.ui.setStatus(
2507
+ "fabric-prewalk",
2508
+ prewalkStatus.state === "armed" ? `plan awaited \u2192 ${prewalkStatus.model}` : void 0
2485
2509
  );
2486
2510
  }
2487
- } else if (state.prewalk.planRequired(boundarySessionId)) {
2488
- const prewalkStatus = state.prewalk.status();
2489
- context.ui.setStatus(
2490
- "fabric-prewalk",
2491
- prewalkStatus.state === "armed" ? `plan awaited \u2192 ${prewalkStatus.model}` : void 0
2511
+ const fullFormattedValue = formatFabricValue(result.value, selectedResultFormat);
2512
+ const failureProgress = formatFailureProgress(result.trace);
2513
+ const fullSections = [...result.logs];
2514
+ if (fullFormattedValue.text) fullSections.push(fullFormattedValue.text);
2515
+ if (result.error) fullSections.push(`Runtime error: ${result.error}`);
2516
+ if (failureProgress) fullSections.push(failureProgress);
2517
+ if (repeat.warn) fullSections.push(fabricRepeatWarnText(repeat.count, FABRIC_REPEAT_BLOCK));
2518
+ const fullRawOutput = fullSections.join("\n\n");
2519
+ const outputBudget = modelOutputBudget(
2520
+ Math.min(
2521
+ state.config.executor.maxOutputChars,
2522
+ (params.maxOutputTokens ?? params.max_output_tokens ?? Infinity) * 4,
2523
+ detached ? FABRIC_DETACHED_OUTPUT_CHARS : Infinity
2524
+ ),
2525
+ result.success
2492
2526
  );
2493
- }
2494
- const fullFormattedValue = formatFabricValue(result.value, selectedResultFormat);
2495
- const failureProgress = formatFailureProgress(result.trace);
2496
- const fullSections = [...result.logs];
2497
- if (fullFormattedValue.text) fullSections.push(fullFormattedValue.text);
2498
- if (result.error) fullSections.push(`Runtime error: ${result.error}`);
2499
- if (failureProgress) fullSections.push(failureProgress);
2500
- if (repeat.warn) fullSections.push(fabricRepeatWarnText(repeat.count, FABRIC_REPEAT_BLOCK));
2501
- const fullRawOutput = fullSections.join("\n\n");
2502
- const outputBudget = modelOutputBudget(
2503
- Math.min(state.config.executor.maxOutputChars, (params.maxOutputTokens ?? params.max_output_tokens ?? Infinity) * 4),
2504
- result.success
2505
- );
2506
- const outputWillTruncate = fullRawOutput.length > outputBudget;
2507
- const formattedValue = outputWillTruncate ? formatFabricValue(
2508
- result.value,
2509
- selectedResultFormat,
2510
- outputBudget
2511
- ) : fullFormattedValue;
2512
- const sections = [...result.logs];
2513
- const logPrefix = result.logs.join("\n\n");
2514
- if (formattedValue.text) sections.push(formattedValue.text);
2515
- if (result.error) sections.push(`Runtime error: ${result.error}`);
2516
- if (failureProgress) sections.push(failureProgress);
2517
- if (repeat.warn) sections.push(fabricRepeatWarnText(repeat.count, FABRIC_REPEAT_BLOCK));
2518
- const rawOutput = sections.join("\n\n");
2519
- const outputFormat = formattedValue.language && formattedValue.text && (result.logs.length === 0 || !outputWillTruncate) ? formattedValue.language : void 0;
2520
- const outputFormatStartLine = result.logs.length > 0 ? countNewlines(logPrefix) + 2 : 0;
2521
- const persistedRenderDetails = () => createFabricPersistedExecutionDetails({
2522
- ...result,
2523
- ...outputFormat ? { outputFormat, outputFormatStartLine } : {},
2524
- ...outputFormat ? {
2525
- outputFormatLines: formattedValue.highlightedLineCount ?? countNewlines(formattedValue.text) + 1
2526
- } : {}
2527
- });
2528
- if (result.typeErrors) {
2529
- const text = result.typeErrors.map(
2530
- (error) => error.line > 0 ? `Line ${error.line}:${error.column} \u2014 ${error.message}` : error.message
2531
- ).join("\n");
2532
- const { typeErrorRecoveryHint } = await import("../type-error-guidance.js");
2533
- const recoveryHint = typeErrorRecoveryHint(code, result.typeErrors);
2534
- const bounded = await boundModelOutput(
2535
- `Type errors; code was not executed:
2527
+ const outputWillTruncate = fullRawOutput.length > outputBudget;
2528
+ const formattedValue = outputWillTruncate ? formatFabricValue(
2529
+ result.value,
2530
+ selectedResultFormat,
2531
+ outputBudget
2532
+ ) : fullFormattedValue;
2533
+ const sections = [...result.logs];
2534
+ const logPrefix = result.logs.join("\n\n");
2535
+ if (formattedValue.text) sections.push(formattedValue.text);
2536
+ if (result.error) sections.push(`Runtime error: ${result.error}`);
2537
+ if (failureProgress) sections.push(failureProgress);
2538
+ if (repeat.warn) sections.push(fabricRepeatWarnText(repeat.count, FABRIC_REPEAT_BLOCK));
2539
+ const rawOutput = sections.join("\n\n");
2540
+ const outputFormat = formattedValue.language && formattedValue.text && (result.logs.length === 0 || !outputWillTruncate) ? formattedValue.language : void 0;
2541
+ const outputFormatStartLine = result.logs.length > 0 ? countNewlines(logPrefix) + 2 : 0;
2542
+ const persistedRenderDetails = () => createFabricPersistedExecutionDetails({
2543
+ ...result,
2544
+ ...outputFormat ? { outputFormat, outputFormatStartLine } : {},
2545
+ ...outputFormat ? {
2546
+ outputFormatLines: formattedValue.highlightedLineCount ?? countNewlines(formattedValue.text) + 1
2547
+ } : {}
2548
+ });
2549
+ if (result.typeErrors) {
2550
+ const text = result.typeErrors.map(
2551
+ (error) => error.line > 0 ? `Line ${error.line}:${error.column} \u2014 ${error.message}` : error.message
2552
+ ).join("\n");
2553
+ const { typeErrorRecoveryHint } = await import("../type-error-guidance.js");
2554
+ const recoveryHint = typeErrorRecoveryHint(code, result.typeErrors);
2555
+ const bounded = await boundModelOutput(
2556
+ `Type errors; code was not executed:
2536
2557
  ${text}${recoveryHint ? `
2537
2558
 
2538
2559
  ${recoveryHint}` : ""}`,
2539
- outputBudget
2540
- );
2560
+ outputBudget
2561
+ );
2562
+ return {
2563
+ content: [{ type: "text", text: bounded.text }],
2564
+ details: persistedRenderDetails(),
2565
+ isError: true
2566
+ };
2567
+ }
2568
+ const output = (await boundModelOutput(
2569
+ rawOutput || "(no output)",
2570
+ outputBudget,
2571
+ fullRawOutput || "(no output)"
2572
+ )).text;
2573
+ const inPlaceContinuation = pendingHandoff?.kind === "prewalk-in-place";
2574
+ const terminate = !inPlaceContinuation && (pendingHandoff !== void 0 || result.success && typeof result.value === "object" && result.value !== null && "terminate" in result.value && result.value.terminate === true);
2575
+ const mediaBlocks = [];
2576
+ for (const block of result.media ?? []) mediaBlocks.push(block);
2577
+ for (const audit of result.audits) {
2578
+ if (audit.media) mediaBlocks.push(...audit.media);
2579
+ }
2580
+ const singleAudit = result.audits.length === 1 ? result.audits[0] : void 0;
2581
+ const mediaNote = singleAudit?.mediaNote;
2582
+ for (const audit of result.audits) {
2583
+ delete audit.media;
2584
+ delete audit.mediaNote;
2585
+ }
2586
+ const content = [];
2587
+ if (mediaBlocks.length > 0) {
2588
+ const textOutput = singleAudit && mediaNote ? mediaNote : output === "(no output)" ? "" : output;
2589
+ if (textOutput) content.push({ type: "text", text: textOutput });
2590
+ for (const block of mediaBlocks) content.push(block);
2591
+ if (singleAudit && mediaNote) {
2592
+ singleAudit.result = mediaNote;
2593
+ }
2594
+ } else {
2595
+ content.push({ type: "text", text: output });
2596
+ }
2541
2597
  return {
2542
- content: [{ type: "text", text: bounded.text }],
2598
+ content,
2543
2599
  details: persistedRenderDetails(),
2544
- isError: true
2600
+ ...result.usage ? { usage: result.usage } : {},
2601
+ ...terminate ? { terminate: true } : {},
2602
+ ...result.success ? {} : { isError: true }
2545
2603
  };
2546
- }
2547
- const output = (await boundModelOutput(
2548
- rawOutput || "(no output)",
2549
- outputBudget,
2550
- fullRawOutput || "(no output)"
2551
- )).text;
2552
- const inPlaceContinuation = pendingHandoff?.kind === "prewalk-in-place";
2553
- const terminate = !inPlaceContinuation && (pendingHandoff !== void 0 || result.success && typeof result.value === "object" && result.value !== null && "terminate" in result.value && result.value.terminate === true);
2554
- const mediaBlocks = [];
2555
- for (const block of result.media ?? []) mediaBlocks.push(block);
2556
- for (const audit of result.audits) {
2557
- if (audit.media) mediaBlocks.push(...audit.media);
2558
- }
2559
- const singleAudit = result.audits.length === 1 ? result.audits[0] : void 0;
2560
- const mediaNote = singleAudit?.mediaNote;
2561
- for (const audit of result.audits) {
2562
- delete audit.media;
2563
- delete audit.mediaNote;
2564
- }
2565
- const content = [];
2566
- if (mediaBlocks.length > 0) {
2567
- const textOutput = singleAudit && mediaNote ? mediaNote : output === "(no output)" ? "" : output;
2568
- if (textOutput) content.push({ type: "text", text: textOutput });
2569
- for (const block of mediaBlocks) content.push(block);
2570
- if (singleAudit && mediaNote) {
2571
- singleAudit.result = mediaNote;
2572
- }
2573
- } else {
2574
- content.push({ type: "text", text: output });
2575
- }
2576
- return {
2577
- content,
2578
- details: persistedRenderDetails(),
2579
- ...result.usage ? { usage: result.usage } : {},
2580
- ...terminate ? { terminate: true } : {},
2581
- ...result.success ? {} : { isError: true }
2582
2604
  };
2605
+ const raced = program ? await program.race(execution) : { detached: false, value: await execution };
2606
+ if (raced.detached) {
2607
+ void execution.then(
2608
+ async (result) => {
2609
+ const finished = await finishExecution(result, true);
2610
+ const text = finished.content.map((part) => part.type === "text" ? part.text : "[image omitted]").join("\n");
2611
+ await program.complete(text, !finished.isError);
2612
+ },
2613
+ (error) => program.complete(
2614
+ `Runtime error: ${error instanceof Error ? error.message : String(error)}`,
2615
+ false
2616
+ )
2617
+ ).catch(() => void 0);
2618
+ return {
2619
+ content: [{ type: "text", text: fabricDetachedText(raced.job.id, raced.elapsedMs, params.background === true) }],
2620
+ details: void 0
2621
+ };
2622
+ }
2623
+ return finishExecution(raced.value, false);
2583
2624
  }
2584
2625
  }),
2585
2626
  {
@@ -2690,6 +2731,114 @@ var FabricManagedHost = class {
2690
2731
  }
2691
2732
  };
2692
2733
 
2734
+ // src/core/program-tasks.ts
2735
+ var FabricProgramRun = class {
2736
+ constructor(owner, options) {
2737
+ this.owner = owner;
2738
+ this.options = options;
2739
+ const parent = options.parentSignal;
2740
+ if (parent?.aborted) this.#onParentAbort();
2741
+ else parent?.addEventListener("abort", this.#onParentAbort, { once: true });
2742
+ }
2743
+ #relay = new AbortController();
2744
+ #startedAt = Date.now();
2745
+ #onParentAbort = () => {
2746
+ if (!this.#job) this.#relay.abort(this.options.parentSignal?.reason ?? new Error("fabric_exec aborted"));
2747
+ };
2748
+ #job;
2749
+ #settled = false;
2750
+ #progress;
2751
+ #wake;
2752
+ get signal() {
2753
+ return this.#relay.signal;
2754
+ }
2755
+ get job() {
2756
+ return this.#job;
2757
+ }
2758
+ get waiting() {
2759
+ return !this.#job && !this.#settled && !this.#relay.signal.aborted;
2760
+ }
2761
+ /** Moves the program into the session task store; false when it cannot leave. */
2762
+ detach() {
2763
+ if (!this.waiting) return false;
2764
+ const jobs = this.options.jobs();
2765
+ if (!jobs) return false;
2766
+ let job;
2767
+ try {
2768
+ job = jobs.begin("fabric_exec", this.options.code, {
2769
+ ...this.options.description ? { description: this.options.description } : {},
2770
+ ...this.options.cwd ? { cwd: this.options.cwd } : {}
2771
+ });
2772
+ } catch {
2773
+ return false;
2774
+ }
2775
+ this.#job = job;
2776
+ this.options.parentSignal?.removeEventListener("abort", this.#onParentAbort);
2777
+ job.abort.signal.addEventListener("abort", () => this.#relay.abort(job.abort.signal.reason), { once: true });
2778
+ if (this.#progress) job.append(Buffer.from(`${this.#progress}
2779
+ `));
2780
+ job.spill();
2781
+ void job.persistLog().catch(() => void 0);
2782
+ this.owner.release(this);
2783
+ this.#wake?.();
2784
+ return true;
2785
+ }
2786
+ /** Mirrors changed progress into the task's output once detached. */
2787
+ progress(text) {
2788
+ if (!text || text === this.#progress) return;
2789
+ this.#progress = text;
2790
+ this.#job?.append(Buffer.from(`${text}
2791
+ `));
2792
+ }
2793
+ /** Settles with the program, or earlier when it is detached. */
2794
+ async race(work) {
2795
+ const detached = new Promise((resolve) => {
2796
+ this.#wake = () => resolve("detached");
2797
+ if (this.#job) resolve("detached");
2798
+ });
2799
+ const first = await Promise.race([
2800
+ work.then((value) => ({ value }), (error) => ({ error })),
2801
+ detached
2802
+ ]);
2803
+ if (first === "detached") return { detached: true, job: this.#job, elapsedMs: Date.now() - this.#startedAt };
2804
+ this.#settled = true;
2805
+ this.owner.release(this);
2806
+ if ("error" in first) throw first.error;
2807
+ return { detached: false, value: first.value };
2808
+ }
2809
+ /** Records the program's final model-facing text and ends the task. */
2810
+ async complete(text, success) {
2811
+ this.#settled = true;
2812
+ const job = this.#job;
2813
+ if (!job || job.finished) return;
2814
+ job.append(Buffer.from(`${text}
2815
+ `));
2816
+ job.exitCode = success ? 0 : 1;
2817
+ await job.finish(job.exitCode);
2818
+ }
2819
+ };
2820
+ var FabricProgramTasks = class {
2821
+ #waiting = /* @__PURE__ */ new Set();
2822
+ begin(options) {
2823
+ const run = new FabricProgramRun(this, options);
2824
+ this.#waiting.add(run);
2825
+ return run;
2826
+ }
2827
+ release(run) {
2828
+ this.#waiting.delete(run);
2829
+ }
2830
+ waiting() {
2831
+ let count = 0;
2832
+ for (const run of this.#waiting) if (run.waiting) count++;
2833
+ return count;
2834
+ }
2835
+ detachWaiting() {
2836
+ let count = 0;
2837
+ for (const run of [...this.#waiting]) if (run.detach()) count++;
2838
+ return count;
2839
+ }
2840
+ };
2841
+
2693
2842
  // src/fabric-state.ts
2694
2843
  var FabricState = class {
2695
2844
  constructor(pi, capturedTools, options = {}) {
@@ -2723,6 +2872,8 @@ var FabricState = class {
2723
2872
  prewalk = new PrewalkController();
2724
2873
  prewalkDrift = new PrewalkDriftTracker();
2725
2874
  sessionApprovals = new FabricSessionApprovals();
2875
+ /** Foreground `fabric_exec` programs the Ctrl+B chord can move to the background. */
2876
+ programTasks = new FabricProgramTasks();
2726
2877
  // agent_end must revert an override even before activation; the controller
2727
2878
  // itself loads only when an override can exist.
2728
2879
  thinking;
@@ -5257,7 +5408,9 @@ function installFabricShellHangKeys(context, options) {
5257
5408
  return void 0;
5258
5409
  }
5259
5410
  const jobs = options.jobs();
5260
- if (!jobs || jobs.waiting().length === 0) {
5411
+ const shells = jobs?.waiting().length ?? 0;
5412
+ const programs = shells === 0 && data === CTRL_B && editorEmpty(context) ? options.programs?.() : void 0;
5413
+ if (!jobs || shells === 0 && !programs?.waiting()) {
5261
5414
  chordArmedAt = 0;
5262
5415
  return void 0;
5263
5416
  }
@@ -5265,6 +5418,16 @@ function installFabricShellHangKeys(context, options) {
5265
5418
  const now = Date.now();
5266
5419
  if (chordArmedAt > 0 && now - chordArmedAt <= CTRL_B_CHORD_MS) {
5267
5420
  chordArmedAt = 0;
5421
+ if (programs) {
5422
+ const count2 = programs.detachWaiting();
5423
+ if (count2 > 0) {
5424
+ context.ui.notify(
5425
+ count2 === 1 ? "Fabric: program moved to the background \xB7 /fabric tasks" : `Fabric: ${count2} programs moved to the background \xB7 /fabric tasks`,
5426
+ "info"
5427
+ );
5428
+ }
5429
+ return { consume: true };
5430
+ }
5268
5431
  const count = jobs.spillWaiting();
5269
5432
  if (count > 0) {
5270
5433
  context.ui.notify(
@@ -5295,6 +5458,13 @@ function installFabricShellHangKeys(context, options) {
5295
5458
  unsubscribe();
5296
5459
  };
5297
5460
  }
5461
+ var editorEmpty = (context) => {
5462
+ try {
5463
+ return (context.ui.getEditorText?.() ?? "") === "";
5464
+ } catch {
5465
+ return false;
5466
+ }
5467
+ };
5298
5468
 
5299
5469
  // src/ui/tool-display.ts
5300
5470
  var FabricToolDisplayController = class {
@@ -5702,7 +5872,8 @@ function createFabricExtension(entryUrl) {
5702
5872
  shellHangKeysUnsubscribe = installFabricShellHangKeys(context, {
5703
5873
  enabled: () => state.initialized,
5704
5874
  ownsInput: () => fabricUi.ownsInput,
5705
- jobs: () => state.shellJobs
5875
+ jobs: () => state.shellJobs,
5876
+ programs: () => state.programTasks
5706
5877
  });
5707
5878
  };
5708
5879
  const refreshProxyLedger = (context) => {
@@ -6350,4 +6521,4 @@ export {
6350
6521
  FABRIC_MANAGED_HOST_VERSION,
6351
6522
  createFabricExtension
6352
6523
  };
6353
- //# sourceMappingURL=chunk-OWR32LJF.js.map
6524
+ //# sourceMappingURL=chunk-SWTFJEPN.js.map