iosm-cli 0.2.5 → 0.2.7

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 (59) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +460 -304
  3. package/dist/cli/args.d.ts.map +1 -1
  4. package/dist/cli/args.js +4 -1
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/core/agent-profiles.d.ts.map +1 -1
  7. package/dist/core/agent-profiles.js +4 -2
  8. package/dist/core/agent-profiles.js.map +1 -1
  9. package/dist/core/agent-session.d.ts.map +1 -1
  10. package/dist/core/agent-session.js +14 -1
  11. package/dist/core/agent-session.js.map +1 -1
  12. package/dist/core/sdk.d.ts +2 -2
  13. package/dist/core/sdk.d.ts.map +1 -1
  14. package/dist/core/sdk.js +3 -3
  15. package/dist/core/sdk.js.map +1 -1
  16. package/dist/core/shadow-guard.js +1 -1
  17. package/dist/core/shadow-guard.js.map +1 -1
  18. package/dist/core/shared-memory.d.ts +14 -0
  19. package/dist/core/shared-memory.d.ts.map +1 -1
  20. package/dist/core/shared-memory.js +63 -0
  21. package/dist/core/shared-memory.js.map +1 -1
  22. package/dist/core/system-prompt.d.ts.map +1 -1
  23. package/dist/core/system-prompt.js +17 -2
  24. package/dist/core/system-prompt.js.map +1 -1
  25. package/dist/core/tools/fetch.d.ts +56 -0
  26. package/dist/core/tools/fetch.d.ts.map +1 -0
  27. package/dist/core/tools/fetch.js +272 -0
  28. package/dist/core/tools/fetch.js.map +1 -0
  29. package/dist/core/tools/fs-ops.d.ts +54 -0
  30. package/dist/core/tools/fs-ops.d.ts.map +1 -0
  31. package/dist/core/tools/fs-ops.js +206 -0
  32. package/dist/core/tools/fs-ops.js.map +1 -0
  33. package/dist/core/tools/git-read.d.ts +60 -0
  34. package/dist/core/tools/git-read.d.ts.map +1 -0
  35. package/dist/core/tools/git-read.js +267 -0
  36. package/dist/core/tools/git-read.js.map +1 -0
  37. package/dist/core/tools/index.d.ts +44 -0
  38. package/dist/core/tools/index.d.ts.map +1 -1
  39. package/dist/core/tools/index.js +22 -0
  40. package/dist/core/tools/index.js.map +1 -1
  41. package/dist/core/tools/shared-memory.d.ts.map +1 -1
  42. package/dist/core/tools/shared-memory.js +45 -5
  43. package/dist/core/tools/shared-memory.js.map +1 -1
  44. package/dist/core/tools/task.d.ts +12 -1
  45. package/dist/core/tools/task.d.ts.map +1 -1
  46. package/dist/core/tools/task.js +565 -9
  47. package/dist/core/tools/task.js.map +1 -1
  48. package/dist/index.d.ts +1 -1
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +1 -1
  51. package/dist/index.js.map +1 -1
  52. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  53. package/dist/modes/interactive/interactive-mode.js +185 -26
  54. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  55. package/docs/cli-reference.md +4 -1
  56. package/docs/configuration.md +2 -2
  57. package/docs/interactive-mode.md +2 -2
  58. package/docs/rpc-json-sdk.md +1 -1
  59. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"shared-memory.js","sourceRoot":"","sources":["../../src/core/shared-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACjG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AA2EvC,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAClC,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAChC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAC5B,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B,MAAM,aAAa,GA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C,CAAC;YACJ,CAAC;YAED,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;YACpE,MAAM,MAAM,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;YAC5C,OAAO;gBACN,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,KAAK,EAAE,MAAM;gBACb,YAAY,EAAE,YAAY,CAAC,MAAM;aACjC,CAAC;QACF,CAAC,EAAE,MAAM,CAAC,CAAC;IACZ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;AACF,CAAC","sourcesContent":["import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\n\nexport type SharedMemoryScope = \"run\" | \"task\";\nexport type SharedMemoryWriteMode = \"set\" | \"append\";\n\nexport interface SharedMemoryWriter {\n\ttaskId?: string;\n\tdelegateId?: string;\n\tprofile?: string;\n}\n\nexport interface SharedMemoryContext {\n\trootCwd: string;\n\trunId: string;\n\ttaskId?: string;\n\tdelegateId?: string;\n\tprofile?: string;\n}\n\ninterface SharedMemoryEntry {\n\tvalue: string;\n\tversion: number;\n\tupdatedAt: string;\n\twriter: SharedMemoryWriter;\n}\n\ninterface SharedMemoryHistoryItem {\n\tkey: string;\n\tscope: SharedMemoryScope;\n\tmode: SharedMemoryWriteMode;\n\tversion: number;\n\tupdatedAt: string;\n\twriter: SharedMemoryWriter;\n}\n\ninterface SharedMemoryStore {\n\trunId: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\tentries: Record<string, SharedMemoryEntry>;\n\thistory: SharedMemoryHistoryItem[];\n}\n\nexport interface SharedMemoryReadItem {\n\tkey: string;\n\tscope: SharedMemoryScope;\n\tvalue?: string;\n\tversion: number;\n\tupdatedAt: string;\n\twriter: SharedMemoryWriter;\n}\n\nexport interface SharedMemoryReadResult {\n\trunId: string;\n\tscope: SharedMemoryScope;\n\titems: SharedMemoryReadItem[];\n\ttotalMatched: number;\n}\n\nexport interface SharedMemoryWriteInput {\n\tkey: string;\n\tvalue: string;\n\tscope: SharedMemoryScope;\n\tmode: SharedMemoryWriteMode;\n\tifVersion?: number;\n}\n\nexport interface SharedMemoryReadInput {\n\tscope: SharedMemoryScope;\n\tkey?: string;\n\tprefix?: string;\n\tlimit?: number;\n\tincludeValues?: boolean;\n}\n\nconst maxEntryCharsDefault = 4000;\nconst maxKeysDefault = 500;\nconst historySizeDefault = 1000;\nconst lockRetryAttempts = 12;\nconst lockRetryDelayMs = 20;\nconst snapshotRetryAttempts = 4;\nconst snapshotRetryDelayMs = 8;\n\nconst maxEntryChars = readBoundedInt(process.env.IOSM_SUBAGENT_SHARED_MEMORY_MAX_ENTRY_CHARS, maxEntryCharsDefault, 64, 20_000);\nconst maxKeys = readBoundedInt(process.env.IOSM_SUBAGENT_SHARED_MEMORY_MAX_KEYS, maxKeysDefault, 10, 20_000);\nconst historySize = readBoundedInt(process.env.IOSM_SUBAGENT_SHARED_MEMORY_HISTORY_SIZE, historySizeDefault, 10, 50_000);\n\nfunction readBoundedInt(raw: string | undefined, fallback: number, min: number, max: number): number {\n\tconst parsed = raw ? Number.parseInt(raw, 10) : fallback;\n\tif (!Number.isInteger(parsed)) return fallback;\n\treturn Math.max(min, Math.min(max, parsed));\n}\n\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n\tif (!signal) {\n\t\treturn new Promise((resolve) => setTimeout(resolve, ms));\n\t}\n\tif (signal.aborted) {\n\t\treturn Promise.reject(new Error(\"Operation aborted\"));\n\t}\n\treturn new Promise((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t};\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nclass Mutex {\n\tprivate locked = false;\n\tprivate readonly waiters: Array<() => void> = [];\n\n\tasync acquire(): Promise<() => void> {\n\t\tif (!this.locked) {\n\t\t\tthis.locked = true;\n\t\t\treturn () => this.release();\n\t\t}\n\t\tawait new Promise<void>((resolve) => this.waiters.push(resolve));\n\t\tthis.locked = true;\n\t\treturn () => this.release();\n\t}\n\n\tprivate release(): void {\n\t\tthis.locked = false;\n\t\tconst next = this.waiters.shift();\n\t\tif (next) {\n\t\t\tnext();\n\t\t}\n\t}\n\n\tisIdle(): boolean {\n\t\treturn !this.locked && this.waiters.length === 0;\n\t}\n}\n\nconst localWriteMutexes = new Map<string, Mutex>();\n\nfunction getOrCreateLocalWriteMutex(filePath: string): Mutex {\n\tconst existing = localWriteMutexes.get(filePath);\n\tif (existing) return existing;\n\tconst created = new Mutex();\n\tlocalWriteMutexes.set(filePath, created);\n\treturn created;\n}\n\nfunction cleanupLocalWriteMutex(filePath: string): void {\n\tconst existing = localWriteMutexes.get(filePath);\n\tif (!existing || !existing.isIdle()) return;\n\tlocalWriteMutexes.delete(filePath);\n}\n\nfunction normalizeRunId(runId: string): string {\n\tconst trimmed = runId.trim();\n\tif (!trimmed) throw new Error(\"shared memory requires non-empty run_id context\");\n\treturn trimmed;\n}\n\nfunction normalizeKey(key: string): string {\n\tconst normalized = key.trim().replace(/\\s+/g, \" \");\n\tif (!normalized) throw new Error(\"shared memory key must be non-empty\");\n\tif (normalized.length > 240) {\n\t\tthrow new Error(\"shared memory key too long (max 240 chars)\");\n\t}\n\treturn normalized;\n}\n\nfunction resolveScopedKey(context: SharedMemoryContext, scope: SharedMemoryScope, key: string): string {\n\tconst normalizedKey = normalizeKey(key);\n\tif (scope === \"task\") {\n\t\tif (!context.taskId || !context.taskId.trim()) {\n\t\t\tthrow new Error(\"task-scoped shared memory requires task_id context\");\n\t\t}\n\t\treturn `task:${context.taskId.trim()}:${normalizedKey}`;\n\t}\n\treturn `run:${normalizedKey}`;\n}\n\nfunction parseScopedKey(scopedKey: string): { scope: SharedMemoryScope; key: string; taskId?: string } {\n\tif (scopedKey.startsWith(\"task:\")) {\n\t\tconst rest = scopedKey.slice(\"task:\".length);\n\t\tconst split = rest.indexOf(\":\");\n\t\tif (split <= 0) {\n\t\t\treturn { scope: \"task\", key: rest };\n\t\t}\n\t\treturn {\n\t\t\tscope: \"task\",\n\t\t\ttaskId: rest.slice(0, split),\n\t\t\tkey: rest.slice(split + 1),\n\t\t};\n\t}\n\tif (scopedKey.startsWith(\"run:\")) {\n\t\treturn { scope: \"run\", key: scopedKey.slice(\"run:\".length) };\n\t}\n\treturn { scope: \"run\", key: scopedKey };\n}\n\nfunction getSharedMemoryDir(rootCwd: string): string {\n\treturn join(rootCwd, \".iosm\", \"subagents\", \"shared-memory\");\n}\n\nexport function getSharedMemoryPath(rootCwd: string, runId: string): string {\n\treturn join(getSharedMemoryDir(rootCwd), `${normalizeRunId(runId)}.json`);\n}\n\nfunction createInitialStore(runId: string): SharedMemoryStore {\n\tconst now = new Date().toISOString();\n\treturn {\n\t\trunId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tentries: {},\n\t\thistory: [],\n\t};\n}\n\nfunction normalizeParsedStore(runId: string, parsed: unknown): SharedMemoryStore {\n\tif (!parsed || typeof parsed !== \"object\") return createInitialStore(runId);\n\tconst cast = parsed as SharedMemoryStore;\n\tif (cast.runId !== runId) return createInitialStore(runId);\n\tif (!cast.entries || typeof cast.entries !== \"object\") cast.entries = {};\n\tif (!Array.isArray(cast.history)) cast.history = [];\n\tif (!cast.createdAt || typeof cast.createdAt !== \"string\") cast.createdAt = new Date().toISOString();\n\tif (!cast.updatedAt || typeof cast.updatedAt !== \"string\") cast.updatedAt = cast.createdAt;\n\treturn cast;\n}\n\nfunction readStore(filePath: string, runId: string): SharedMemoryStore {\n\tif (!existsSync(filePath)) {\n\t\treturn createInitialStore(runId);\n\t}\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(filePath, \"utf8\"));\n\t\treturn normalizeParsedStore(runId, parsed);\n\t} catch {\n\t\treturn createInitialStore(runId);\n\t}\n}\n\nasync function readStoreSnapshot(filePath: string, runId: string, signal?: AbortSignal): Promise<SharedMemoryStore> {\n\tif (!existsSync(filePath)) {\n\t\treturn createInitialStore(runId);\n\t}\n\tfor (let attempt = 1; attempt <= snapshotRetryAttempts; attempt += 1) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(readFileSync(filePath, \"utf8\"));\n\t\t\treturn normalizeParsedStore(runId, parsed);\n\t\t} catch {\n\t\t\tif (attempt >= snapshotRetryAttempts) break;\n\t\t\tawait delay(snapshotRetryDelayMs * attempt, signal);\n\t\t}\n\t}\n\treturn createInitialStore(runId);\n}\n\nfunction writeStore(filePath: string, store: SharedMemoryStore): void {\n\tmkdirSync(dirname(filePath), { recursive: true });\n\tconst tempPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;\n\ttry {\n\t\twriteFileSync(tempPath, `${JSON.stringify(store, null, 2)}\\n`, \"utf8\");\n\t\trenameSync(tempPath, filePath);\n\t} finally {\n\t\tif (existsSync(tempPath)) {\n\t\t\trmSync(tempPath, { force: true });\n\t\t}\n\t}\n}\n\nasync function acquireFileLock(filePath: string, signal?: AbortSignal): Promise<() => Promise<void>> {\n\tfor (let attempt = 1; attempt <= lockRetryAttempts; attempt += 1) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\ttry {\n\t\t\treturn await lockfile.lock(filePath, { realpath: false });\n\t\t} catch (error) {\n\t\t\tconst code = error && typeof error === \"object\" && \"code\" in error ? String(error.code) : \"\";\n\t\t\tif (code !== \"ELOCKED\" || attempt >= lockRetryAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait delay(lockRetryDelayMs * attempt, signal);\n\t\t}\n\t}\n\tthrow new Error(\"failed to acquire shared memory lock\");\n}\n\nasync function withLockedStore<T>(\n\tcontext: SharedMemoryContext,\n\tfn: (store: SharedMemoryStore, filePath: string) => T,\n\tsignal?: AbortSignal,\n): Promise<T> {\n\tconst runId = normalizeRunId(context.runId);\n\tconst filePath = getSharedMemoryPath(context.rootCwd, runId);\n\tconst releaseLocalMutex = await getOrCreateLocalWriteMutex(filePath).acquire();\n\tmkdirSync(dirname(filePath), { recursive: true });\n\tif (!existsSync(filePath)) {\n\t\twriteStore(filePath, createInitialStore(runId));\n\t}\n\tconst release = await acquireFileLock(filePath, signal);\n\ttry {\n\t\tconst store = readStore(filePath, runId);\n\t\tconst value = fn(store, filePath);\n\t\twriteStore(filePath, store);\n\t\treturn value;\n\t} finally {\n\t\ttry {\n\t\t\tawait release();\n\t\t} finally {\n\t\t\treleaseLocalMutex();\n\t\t\tcleanupLocalWriteMutex(filePath);\n\t\t}\n\t}\n}\n\nasync function withSnapshotStore<T>(\n\tcontext: SharedMemoryContext,\n\tfn: (store: SharedMemoryStore, filePath: string) => T,\n\tsignal?: AbortSignal,\n): Promise<T> {\n\tconst runId = normalizeRunId(context.runId);\n\tconst filePath = getSharedMemoryPath(context.rootCwd, runId);\n\tconst store = await readStoreSnapshot(filePath, runId, signal);\n\treturn fn(store, filePath);\n}\n\nfunction isAbortError(error: unknown): boolean {\n\tif (error instanceof Error) return /aborted/i.test(error.message);\n\tif (typeof error === \"string\") return /aborted/i.test(error);\n\treturn false;\n}\n\nfunction normalizeLockError(error: unknown): never {\n\tif (isAbortError(error)) {\n\t\tthrow new Error(\"Operation aborted\");\n\t}\n\tthrow error;\n}\n\nfunction trimHistory(store: SharedMemoryStore): void {\n\tif (store.history.length <= historySize) return;\n\tstore.history = store.history.slice(store.history.length - historySize);\n}\n\nfunction writerFromContext(context: SharedMemoryContext): SharedMemoryWriter {\n\treturn {\n\t\ttaskId: context.taskId?.trim() || undefined,\n\t\tdelegateId: context.delegateId?.trim() || undefined,\n\t\tprofile: context.profile?.trim() || undefined,\n\t};\n}\n\nexport async function writeSharedMemory(\n\tcontext: SharedMemoryContext,\n\tinput: SharedMemoryWriteInput,\n\tsignal?: AbortSignal,\n): Promise<SharedMemoryReadItem> {\n\tconst normalizedValue = input.value;\n\tif (normalizedValue.length > maxEntryChars) {\n\t\tthrow new Error(`shared memory value exceeds ${maxEntryChars} chars`);\n\t}\n\tconst scopedKey = resolveScopedKey(context, input.scope, input.key);\n\ttry {\n\t\treturn await withLockedStore(context, (store) => {\n\t\tconst now = new Date().toISOString();\n\t\tconst entriesCount = Object.keys(store.entries).length;\n\t\tconst previous = store.entries[scopedKey];\n\t\tif (!previous && entriesCount >= maxKeys) {\n\t\t\tthrow new Error(`shared memory key limit reached (${maxKeys})`);\n\t\t}\n\t\tif (input.ifVersion !== undefined && previous && previous.version !== input.ifVersion) {\n\t\t\tthrow new Error(`shared memory CAS mismatch for key \"${input.key}\" (expected ${input.ifVersion}, got ${previous.version})`);\n\t\t}\n\t\tif (input.ifVersion !== undefined && !previous) {\n\t\t\tthrow new Error(`shared memory CAS mismatch for key \"${input.key}\" (expected ${input.ifVersion}, got 0)`);\n\t\t}\n\n\t\tconst nextValue = input.mode === \"append\" ? `${previous?.value ?? \"\"}${normalizedValue}` : normalizedValue;\n\t\tif (nextValue.length > maxEntryChars) {\n\t\t\tthrow new Error(`shared memory value exceeds ${maxEntryChars} chars after ${input.mode}`);\n\t\t}\n\t\tconst nextVersion = (previous?.version ?? 0) + 1;\n\t\tconst writer = writerFromContext(context);\n\t\tstore.entries[scopedKey] = {\n\t\t\tvalue: nextValue,\n\t\t\tversion: nextVersion,\n\t\t\tupdatedAt: now,\n\t\t\twriter,\n\t\t};\n\t\tstore.updatedAt = now;\n\t\tstore.history.push({\n\t\t\tkey: normalizeKey(input.key),\n\t\t\tscope: input.scope,\n\t\t\tmode: input.mode,\n\t\t\tversion: nextVersion,\n\t\t\tupdatedAt: now,\n\t\t\twriter,\n\t\t});\n\t\ttrimHistory(store);\n\n\t\treturn {\n\t\t\tkey: normalizeKey(input.key),\n\t\t\tscope: input.scope,\n\t\t\tvalue: nextValue,\n\t\t\tversion: nextVersion,\n\t\t\tupdatedAt: now,\n\t\t\twriter,\n\t\t};\n\t\t}, signal);\n\t} catch (error) {\n\t\tnormalizeLockError(error);\n\t}\n}\n\nfunction matchesScopeAndPrefix(\n\tcontext: SharedMemoryContext,\n\tscopedKey: string,\n\tscope: SharedMemoryScope,\n\tkey: string | undefined,\n\tprefix: string | undefined,\n): { matched: boolean; parsed: ReturnType<typeof parseScopedKey> } {\n\tconst parsed = parseScopedKey(scopedKey);\n\tif (parsed.scope !== scope) return { matched: false, parsed };\n\tif (scope === \"task\") {\n\t\tconst taskId = context.taskId?.trim();\n\t\tif (!taskId) return { matched: false, parsed };\n\t\tif (parsed.taskId !== taskId) return { matched: false, parsed };\n\t}\n\tif (key) {\n\t\treturn { matched: parsed.key === key, parsed };\n\t}\n\tif (prefix) {\n\t\treturn { matched: parsed.key.startsWith(prefix), parsed };\n\t}\n\treturn { matched: true, parsed };\n}\n\nexport async function readSharedMemory(\n\tcontext: SharedMemoryContext,\n\tinput: SharedMemoryReadInput,\n\tsignal?: AbortSignal,\n): Promise<SharedMemoryReadResult> {\n\tconst normalizedKey = input.key ? normalizeKey(input.key) : undefined;\n\tconst normalizedPrefix = input.prefix ? normalizeKey(input.prefix) : undefined;\n\tconst limit = Math.max(1, Math.min(100, input.limit ?? 20));\n\tconst includeValues = input.includeValues !== false;\n\n\ttry {\n\t\treturn await withSnapshotStore(context, (store) => {\n\t\tconst matchedItems: SharedMemoryReadItem[] = [];\n\t\tfor (const [scopedKey, entry] of Object.entries(store.entries)) {\n\t\t\tconst matched = matchesScopeAndPrefix(context, scopedKey, input.scope, normalizedKey, normalizedPrefix);\n\t\t\tif (!matched.matched) continue;\n\t\t\tmatchedItems.push({\n\t\t\t\tkey: matched.parsed.key,\n\t\t\t\tscope: input.scope,\n\t\t\t\tvalue: includeValues ? entry.value : undefined,\n\t\t\t\tversion: entry.version,\n\t\t\t\tupdatedAt: entry.updatedAt,\n\t\t\t\twriter: entry.writer ?? {},\n\t\t\t});\n\t\t}\n\n\t\tmatchedItems.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));\n\t\tconst sliced = matchedItems.slice(0, limit);\n\t\treturn {\n\t\t\trunId: store.runId,\n\t\t\tscope: input.scope,\n\t\t\titems: sliced,\n\t\t\ttotalMatched: matchedItems.length,\n\t\t};\n\t\t}, signal);\n\t} catch (error) {\n\t\tnormalizeLockError(error);\n\t}\n}\n"]}
1
+ {"version":3,"file":"shared-memory.js","sourceRoot":"","sources":["../../src/core/shared-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACjG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AAyFvC,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAClC,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAChC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAC5B,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B,MAAM,aAAa,GAAG,cAAc,CAAC,OAAO,CAAC,GAAG,CAAC,2CAA2C,EAAE,oBAAoB,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;AAChI,MAAM,OAAO,GAAG,cAAc,CAAC,OAAO,CAAC,GAAG,C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aAAa,EAAE,SAAS,CAAC,IAAI;gBAC7B,UAAU,EAAE,MAAM,CAAC,IAAI;aACvB,CAAC;QACH,CAAC,EACD,MAAM,CACN,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;AACF,CAAC","sourcesContent":["import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\n\nexport type SharedMemoryScope = \"run\" | \"task\";\nexport type SharedMemoryWriteMode = \"set\" | \"append\";\n\nexport interface SharedMemoryWriter {\n\ttaskId?: string;\n\tdelegateId?: string;\n\tprofile?: string;\n}\n\nexport interface SharedMemoryContext {\n\trootCwd: string;\n\trunId: string;\n\ttaskId?: string;\n\tdelegateId?: string;\n\tprofile?: string;\n}\n\ninterface SharedMemoryEntry {\n\tvalue: string;\n\tversion: number;\n\tupdatedAt: string;\n\twriter: SharedMemoryWriter;\n}\n\ninterface SharedMemoryHistoryItem {\n\tkey: string;\n\tscope: SharedMemoryScope;\n\tmode: SharedMemoryWriteMode;\n\tversion: number;\n\tupdatedAt: string;\n\twriter: SharedMemoryWriter;\n}\n\ninterface SharedMemoryStore {\n\trunId: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\tentries: Record<string, SharedMemoryEntry>;\n\thistory: SharedMemoryHistoryItem[];\n}\n\nexport interface SharedMemoryReadItem {\n\tkey: string;\n\tscope: SharedMemoryScope;\n\tvalue?: string;\n\tversion: number;\n\tupdatedAt: string;\n\twriter: SharedMemoryWriter;\n}\n\nexport interface SharedMemoryReadResult {\n\trunId: string;\n\tscope: SharedMemoryScope;\n\titems: SharedMemoryReadItem[];\n\ttotalMatched: number;\n}\n\nexport interface SharedMemoryUsageSummary {\n\trunId: string;\n\ttotalEntries: number;\n\ttotalWrites: number;\n\trunScopeWrites: number;\n\ttaskScopeWrites: number;\n\tcurrentTaskWrites: number;\n\tcurrentTaskRunScopeWrites: number;\n\tcurrentTaskTaskScopeWrites: number;\n\tcurrentTaskDelegateWrites: number;\n\tuniqueWriters: number;\n\tuniqueKeys: number;\n}\n\nexport interface SharedMemoryWriteInput {\n\tkey: string;\n\tvalue: string;\n\tscope: SharedMemoryScope;\n\tmode: SharedMemoryWriteMode;\n\tifVersion?: number;\n}\n\nexport interface SharedMemoryReadInput {\n\tscope: SharedMemoryScope;\n\tkey?: string;\n\tprefix?: string;\n\tlimit?: number;\n\tincludeValues?: boolean;\n}\n\nconst maxEntryCharsDefault = 4000;\nconst maxKeysDefault = 500;\nconst historySizeDefault = 1000;\nconst lockRetryAttempts = 12;\nconst lockRetryDelayMs = 20;\nconst snapshotRetryAttempts = 4;\nconst snapshotRetryDelayMs = 8;\n\nconst maxEntryChars = readBoundedInt(process.env.IOSM_SUBAGENT_SHARED_MEMORY_MAX_ENTRY_CHARS, maxEntryCharsDefault, 64, 20_000);\nconst maxKeys = readBoundedInt(process.env.IOSM_SUBAGENT_SHARED_MEMORY_MAX_KEYS, maxKeysDefault, 10, 20_000);\nconst historySize = readBoundedInt(process.env.IOSM_SUBAGENT_SHARED_MEMORY_HISTORY_SIZE, historySizeDefault, 10, 50_000);\n\nfunction readBoundedInt(raw: string | undefined, fallback: number, min: number, max: number): number {\n\tconst parsed = raw ? Number.parseInt(raw, 10) : fallback;\n\tif (!Number.isInteger(parsed)) return fallback;\n\treturn Math.max(min, Math.min(max, parsed));\n}\n\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n\tif (!signal) {\n\t\treturn new Promise((resolve) => setTimeout(resolve, ms));\n\t}\n\tif (signal.aborted) {\n\t\treturn Promise.reject(new Error(\"Operation aborted\"));\n\t}\n\treturn new Promise((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t};\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nclass Mutex {\n\tprivate locked = false;\n\tprivate readonly waiters: Array<() => void> = [];\n\n\tasync acquire(): Promise<() => void> {\n\t\tif (!this.locked) {\n\t\t\tthis.locked = true;\n\t\t\treturn () => this.release();\n\t\t}\n\t\tawait new Promise<void>((resolve) => this.waiters.push(resolve));\n\t\tthis.locked = true;\n\t\treturn () => this.release();\n\t}\n\n\tprivate release(): void {\n\t\tthis.locked = false;\n\t\tconst next = this.waiters.shift();\n\t\tif (next) {\n\t\t\tnext();\n\t\t}\n\t}\n\n\tisIdle(): boolean {\n\t\treturn !this.locked && this.waiters.length === 0;\n\t}\n}\n\nconst localWriteMutexes = new Map<string, Mutex>();\n\nfunction getOrCreateLocalWriteMutex(filePath: string): Mutex {\n\tconst existing = localWriteMutexes.get(filePath);\n\tif (existing) return existing;\n\tconst created = new Mutex();\n\tlocalWriteMutexes.set(filePath, created);\n\treturn created;\n}\n\nfunction cleanupLocalWriteMutex(filePath: string): void {\n\tconst existing = localWriteMutexes.get(filePath);\n\tif (!existing || !existing.isIdle()) return;\n\tlocalWriteMutexes.delete(filePath);\n}\n\nfunction normalizeRunId(runId: string): string {\n\tconst trimmed = runId.trim();\n\tif (!trimmed) throw new Error(\"shared memory requires non-empty run_id context\");\n\treturn trimmed;\n}\n\nfunction normalizeKey(key: string): string {\n\tconst normalized = key.trim().replace(/\\s+/g, \" \");\n\tif (!normalized) throw new Error(\"shared memory key must be non-empty\");\n\tif (normalized.length > 240) {\n\t\tthrow new Error(\"shared memory key too long (max 240 chars)\");\n\t}\n\treturn normalized;\n}\n\nfunction resolveScopedKey(context: SharedMemoryContext, scope: SharedMemoryScope, key: string): string {\n\tconst normalizedKey = normalizeKey(key);\n\tif (scope === \"task\") {\n\t\tif (!context.taskId || !context.taskId.trim()) {\n\t\t\tthrow new Error(\"task-scoped shared memory requires task_id context\");\n\t\t}\n\t\treturn `task:${context.taskId.trim()}:${normalizedKey}`;\n\t}\n\treturn `run:${normalizedKey}`;\n}\n\nfunction parseScopedKey(scopedKey: string): { scope: SharedMemoryScope; key: string; taskId?: string } {\n\tif (scopedKey.startsWith(\"task:\")) {\n\t\tconst rest = scopedKey.slice(\"task:\".length);\n\t\tconst split = rest.indexOf(\":\");\n\t\tif (split <= 0) {\n\t\t\treturn { scope: \"task\", key: rest };\n\t\t}\n\t\treturn {\n\t\t\tscope: \"task\",\n\t\t\ttaskId: rest.slice(0, split),\n\t\t\tkey: rest.slice(split + 1),\n\t\t};\n\t}\n\tif (scopedKey.startsWith(\"run:\")) {\n\t\treturn { scope: \"run\", key: scopedKey.slice(\"run:\".length) };\n\t}\n\treturn { scope: \"run\", key: scopedKey };\n}\n\nfunction getSharedMemoryDir(rootCwd: string): string {\n\treturn join(rootCwd, \".iosm\", \"subagents\", \"shared-memory\");\n}\n\nexport function getSharedMemoryPath(rootCwd: string, runId: string): string {\n\treturn join(getSharedMemoryDir(rootCwd), `${normalizeRunId(runId)}.json`);\n}\n\nfunction createInitialStore(runId: string): SharedMemoryStore {\n\tconst now = new Date().toISOString();\n\treturn {\n\t\trunId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tentries: {},\n\t\thistory: [],\n\t};\n}\n\nfunction normalizeParsedStore(runId: string, parsed: unknown): SharedMemoryStore {\n\tif (!parsed || typeof parsed !== \"object\") return createInitialStore(runId);\n\tconst cast = parsed as SharedMemoryStore;\n\tif (cast.runId !== runId) return createInitialStore(runId);\n\tif (!cast.entries || typeof cast.entries !== \"object\") cast.entries = {};\n\tif (!Array.isArray(cast.history)) cast.history = [];\n\tif (!cast.createdAt || typeof cast.createdAt !== \"string\") cast.createdAt = new Date().toISOString();\n\tif (!cast.updatedAt || typeof cast.updatedAt !== \"string\") cast.updatedAt = cast.createdAt;\n\treturn cast;\n}\n\nfunction readStore(filePath: string, runId: string): SharedMemoryStore {\n\tif (!existsSync(filePath)) {\n\t\treturn createInitialStore(runId);\n\t}\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(filePath, \"utf8\"));\n\t\treturn normalizeParsedStore(runId, parsed);\n\t} catch {\n\t\treturn createInitialStore(runId);\n\t}\n}\n\nasync function readStoreSnapshot(filePath: string, runId: string, signal?: AbortSignal): Promise<SharedMemoryStore> {\n\tif (!existsSync(filePath)) {\n\t\treturn createInitialStore(runId);\n\t}\n\tfor (let attempt = 1; attempt <= snapshotRetryAttempts; attempt += 1) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(readFileSync(filePath, \"utf8\"));\n\t\t\treturn normalizeParsedStore(runId, parsed);\n\t\t} catch {\n\t\t\tif (attempt >= snapshotRetryAttempts) break;\n\t\t\tawait delay(snapshotRetryDelayMs * attempt, signal);\n\t\t}\n\t}\n\treturn createInitialStore(runId);\n}\n\nfunction writeStore(filePath: string, store: SharedMemoryStore): void {\n\tmkdirSync(dirname(filePath), { recursive: true });\n\tconst tempPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;\n\ttry {\n\t\twriteFileSync(tempPath, `${JSON.stringify(store, null, 2)}\\n`, \"utf8\");\n\t\trenameSync(tempPath, filePath);\n\t} finally {\n\t\tif (existsSync(tempPath)) {\n\t\t\trmSync(tempPath, { force: true });\n\t\t}\n\t}\n}\n\nasync function acquireFileLock(filePath: string, signal?: AbortSignal): Promise<() => Promise<void>> {\n\tfor (let attempt = 1; attempt <= lockRetryAttempts; attempt += 1) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\ttry {\n\t\t\treturn await lockfile.lock(filePath, { realpath: false });\n\t\t} catch (error) {\n\t\t\tconst code = error && typeof error === \"object\" && \"code\" in error ? String(error.code) : \"\";\n\t\t\tif (code !== \"ELOCKED\" || attempt >= lockRetryAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait delay(lockRetryDelayMs * attempt, signal);\n\t\t}\n\t}\n\tthrow new Error(\"failed to acquire shared memory lock\");\n}\n\nasync function withLockedStore<T>(\n\tcontext: SharedMemoryContext,\n\tfn: (store: SharedMemoryStore, filePath: string) => T,\n\tsignal?: AbortSignal,\n): Promise<T> {\n\tconst runId = normalizeRunId(context.runId);\n\tconst filePath = getSharedMemoryPath(context.rootCwd, runId);\n\tconst releaseLocalMutex = await getOrCreateLocalWriteMutex(filePath).acquire();\n\tmkdirSync(dirname(filePath), { recursive: true });\n\tif (!existsSync(filePath)) {\n\t\twriteStore(filePath, createInitialStore(runId));\n\t}\n\tconst release = await acquireFileLock(filePath, signal);\n\ttry {\n\t\tconst store = readStore(filePath, runId);\n\t\tconst value = fn(store, filePath);\n\t\twriteStore(filePath, store);\n\t\treturn value;\n\t} finally {\n\t\ttry {\n\t\t\tawait release();\n\t\t} finally {\n\t\t\treleaseLocalMutex();\n\t\t\tcleanupLocalWriteMutex(filePath);\n\t\t}\n\t}\n}\n\nasync function withSnapshotStore<T>(\n\tcontext: SharedMemoryContext,\n\tfn: (store: SharedMemoryStore, filePath: string) => T,\n\tsignal?: AbortSignal,\n): Promise<T> {\n\tconst runId = normalizeRunId(context.runId);\n\tconst filePath = getSharedMemoryPath(context.rootCwd, runId);\n\tconst store = await readStoreSnapshot(filePath, runId, signal);\n\treturn fn(store, filePath);\n}\n\nfunction isAbortError(error: unknown): boolean {\n\tif (error instanceof Error) return /aborted/i.test(error.message);\n\tif (typeof error === \"string\") return /aborted/i.test(error);\n\treturn false;\n}\n\nfunction normalizeLockError(error: unknown): never {\n\tif (isAbortError(error)) {\n\t\tthrow new Error(\"Operation aborted\");\n\t}\n\tthrow error;\n}\n\nfunction trimHistory(store: SharedMemoryStore): void {\n\tif (store.history.length <= historySize) return;\n\tstore.history = store.history.slice(store.history.length - historySize);\n}\n\nfunction writerFromContext(context: SharedMemoryContext): SharedMemoryWriter {\n\treturn {\n\t\ttaskId: context.taskId?.trim() || undefined,\n\t\tdelegateId: context.delegateId?.trim() || undefined,\n\t\tprofile: context.profile?.trim() || undefined,\n\t};\n}\n\nexport async function writeSharedMemory(\n\tcontext: SharedMemoryContext,\n\tinput: SharedMemoryWriteInput,\n\tsignal?: AbortSignal,\n): Promise<SharedMemoryReadItem> {\n\tconst normalizedValue = input.value;\n\tif (normalizedValue.length > maxEntryChars) {\n\t\tthrow new Error(`shared memory value exceeds ${maxEntryChars} chars`);\n\t}\n\tconst scopedKey = resolveScopedKey(context, input.scope, input.key);\n\ttry {\n\t\treturn await withLockedStore(context, (store) => {\n\t\tconst now = new Date().toISOString();\n\t\tconst entriesCount = Object.keys(store.entries).length;\n\t\tconst previous = store.entries[scopedKey];\n\t\tif (!previous && entriesCount >= maxKeys) {\n\t\t\tthrow new Error(`shared memory key limit reached (${maxKeys})`);\n\t\t}\n\t\tif (input.ifVersion !== undefined && previous && previous.version !== input.ifVersion) {\n\t\t\tthrow new Error(`shared memory CAS mismatch for key \"${input.key}\" (expected ${input.ifVersion}, got ${previous.version})`);\n\t\t}\n\t\tif (input.ifVersion !== undefined && !previous) {\n\t\t\tthrow new Error(`shared memory CAS mismatch for key \"${input.key}\" (expected ${input.ifVersion}, got 0)`);\n\t\t}\n\n\t\tconst nextValue = input.mode === \"append\" ? `${previous?.value ?? \"\"}${normalizedValue}` : normalizedValue;\n\t\tif (nextValue.length > maxEntryChars) {\n\t\t\tthrow new Error(`shared memory value exceeds ${maxEntryChars} chars after ${input.mode}`);\n\t\t}\n\t\tconst nextVersion = (previous?.version ?? 0) + 1;\n\t\tconst writer = writerFromContext(context);\n\t\tstore.entries[scopedKey] = {\n\t\t\tvalue: nextValue,\n\t\t\tversion: nextVersion,\n\t\t\tupdatedAt: now,\n\t\t\twriter,\n\t\t};\n\t\tstore.updatedAt = now;\n\t\tstore.history.push({\n\t\t\tkey: normalizeKey(input.key),\n\t\t\tscope: input.scope,\n\t\t\tmode: input.mode,\n\t\t\tversion: nextVersion,\n\t\t\tupdatedAt: now,\n\t\t\twriter,\n\t\t});\n\t\ttrimHistory(store);\n\n\t\treturn {\n\t\t\tkey: normalizeKey(input.key),\n\t\t\tscope: input.scope,\n\t\t\tvalue: nextValue,\n\t\t\tversion: nextVersion,\n\t\t\tupdatedAt: now,\n\t\t\twriter,\n\t\t};\n\t\t}, signal);\n\t} catch (error) {\n\t\tnormalizeLockError(error);\n\t}\n}\n\nfunction matchesScopeAndPrefix(\n\tcontext: SharedMemoryContext,\n\tscopedKey: string,\n\tscope: SharedMemoryScope,\n\tkey: string | undefined,\n\tprefix: string | undefined,\n): { matched: boolean; parsed: ReturnType<typeof parseScopedKey> } {\n\tconst parsed = parseScopedKey(scopedKey);\n\tif (parsed.scope !== scope) return { matched: false, parsed };\n\tif (scope === \"task\") {\n\t\tconst taskId = context.taskId?.trim();\n\t\tif (!taskId) return { matched: false, parsed };\n\t\tif (parsed.taskId !== taskId) return { matched: false, parsed };\n\t}\n\tif (key) {\n\t\treturn { matched: parsed.key === key, parsed };\n\t}\n\tif (prefix) {\n\t\treturn { matched: parsed.key.startsWith(prefix), parsed };\n\t}\n\treturn { matched: true, parsed };\n}\n\nexport async function readSharedMemory(\n\tcontext: SharedMemoryContext,\n\tinput: SharedMemoryReadInput,\n\tsignal?: AbortSignal,\n): Promise<SharedMemoryReadResult> {\n\tconst normalizedKey = input.key ? normalizeKey(input.key) : undefined;\n\tconst normalizedPrefix = input.prefix ? normalizeKey(input.prefix) : undefined;\n\tconst limit = Math.max(1, Math.min(100, input.limit ?? 20));\n\tconst includeValues = input.includeValues !== false;\n\n\ttry {\n\t\treturn await withSnapshotStore(context, (store) => {\n\t\tconst matchedItems: SharedMemoryReadItem[] = [];\n\t\tfor (const [scopedKey, entry] of Object.entries(store.entries)) {\n\t\t\tconst matched = matchesScopeAndPrefix(context, scopedKey, input.scope, normalizedKey, normalizedPrefix);\n\t\t\tif (!matched.matched) continue;\n\t\t\tmatchedItems.push({\n\t\t\t\tkey: matched.parsed.key,\n\t\t\t\tscope: input.scope,\n\t\t\t\tvalue: includeValues ? entry.value : undefined,\n\t\t\t\tversion: entry.version,\n\t\t\t\tupdatedAt: entry.updatedAt,\n\t\t\t\twriter: entry.writer ?? {},\n\t\t\t});\n\t\t}\n\n\t\tmatchedItems.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));\n\t\tconst sliced = matchedItems.slice(0, limit);\n\t\treturn {\n\t\t\trunId: store.runId,\n\t\t\tscope: input.scope,\n\t\t\titems: sliced,\n\t\t\ttotalMatched: matchedItems.length,\n\t\t};\n\t\t}, signal);\n\t} catch (error) {\n\t\tnormalizeLockError(error);\n\t}\n}\n\nexport async function summarizeSharedMemoryUsage(\n\tcontext: Pick<SharedMemoryContext, \"rootCwd\" | \"runId\" | \"taskId\">,\n\tsignal?: AbortSignal,\n): Promise<SharedMemoryUsageSummary> {\n\ttry {\n\t\treturn await withSnapshotStore(\n\t\t\t{\n\t\t\t\trootCwd: context.rootCwd,\n\t\t\t\trunId: context.runId,\n\t\t\t\ttaskId: context.taskId,\n\t\t\t},\n\t\t\t(store) => {\n\t\t\t\tconst currentTaskId = context.taskId?.trim() || undefined;\n\t\t\t\tlet runScopeWrites = 0;\n\t\t\t\tlet taskScopeWrites = 0;\n\t\t\t\tlet currentTaskWrites = 0;\n\t\t\t\tlet currentTaskRunScopeWrites = 0;\n\t\t\t\tlet currentTaskTaskScopeWrites = 0;\n\t\t\t\tlet currentTaskDelegateWrites = 0;\n\t\t\t\tconst writerSet = new Set<string>();\n\t\t\t\tconst keySet = new Set<string>();\n\n\t\t\t\tfor (const item of store.history) {\n\t\t\t\t\tconst scope = item.scope === \"task\" ? \"task\" : \"run\";\n\t\t\t\t\tif (scope === \"run\") {\n\t\t\t\t\t\trunScopeWrites += 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttaskScopeWrites += 1;\n\t\t\t\t\t}\n\t\t\t\t\tkeySet.add(`${scope}:${item.key}`);\n\t\t\t\t\tconst writerToken = [\n\t\t\t\t\t\titem.writer.taskId?.trim() || \"-\",\n\t\t\t\t\t\titem.writer.delegateId?.trim() || \"-\",\n\t\t\t\t\t\titem.writer.profile?.trim() || \"-\",\n\t\t\t\t\t].join(\"|\");\n\t\t\t\t\twriterSet.add(writerToken);\n\n\t\t\t\t\tif (currentTaskId && item.writer.taskId?.trim() === currentTaskId) {\n\t\t\t\t\t\tcurrentTaskWrites += 1;\n\t\t\t\t\t\tif (scope === \"run\") {\n\t\t\t\t\t\t\tcurrentTaskRunScopeWrites += 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcurrentTaskTaskScopeWrites += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (item.writer.delegateId?.trim()) {\n\t\t\t\t\t\t\tcurrentTaskDelegateWrites += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\trunId: store.runId,\n\t\t\t\t\ttotalEntries: Object.keys(store.entries).length,\n\t\t\t\t\ttotalWrites: store.history.length,\n\t\t\t\t\trunScopeWrites,\n\t\t\t\t\ttaskScopeWrites,\n\t\t\t\t\tcurrentTaskWrites,\n\t\t\t\t\tcurrentTaskRunScopeWrites,\n\t\t\t\t\tcurrentTaskTaskScopeWrites,\n\t\t\t\t\tcurrentTaskDelegateWrites,\n\t\t\t\t\tuniqueWriters: writerSet.size,\n\t\t\t\t\tuniqueKeys: keySet.size,\n\t\t\t\t};\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t} catch (error) {\n\t\tnormalizeLockError(error);\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AA0BhE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;I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AC;IACxD,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;CACjB;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,wBAA6B,GAAG,MAAM,CAqShF"}
@@ -21,6 +21,9 @@ const toolDescriptions = {
21
21
  semgrep: "Run semgrep for structural/static security checks",
22
22
  sed: "Run sed for stream editing/extraction previews (no in-place edits)",
23
23
  semantic_search: "Semantic embeddings search over the project index (actions: status, index, rebuild, query)",
24
+ fetch: "Make HTTP requests with bounded response capture and manual redirect handling",
25
+ git_read: "Structured read-only git introspection (status, diff, log, blame)",
26
+ fs_ops: "Structured filesystem mutations (mkdir, move, copy, delete) with recursive/force guards",
24
27
  task: "Run a specialized subagent (supports profile, cwd, lock_key for optional write serialization, run_id/task_id, model override, background mode for detached runs, and agent=<custom name from .iosm/agents>)",
25
28
  };
26
29
  /** Build the system prompt with tools, guidelines, and context */
@@ -104,6 +107,9 @@ export function buildSystemPrompt(options = {}) {
104
107
  const hasSemgrep = tools.includes("semgrep");
105
108
  const hasSed = tools.includes("sed");
106
109
  const hasSemanticSearch = tools.includes("semantic_search");
110
+ const hasFetch = tools.includes("fetch");
111
+ const hasGitRead = tools.includes("git_read");
112
+ const hasFsOps = tools.includes("fs_ops");
107
113
  const hasRead = tools.includes("read");
108
114
  // File exploration guidelines
109
115
  if (hasBash && !hasGrep && !hasFind && !hasLs && !hasRg && !hasFd) {
@@ -112,8 +118,14 @@ export function buildSystemPrompt(options = {}) {
112
118
  else if (hasBash && (hasGrep || hasFind || hasLs || hasRg || hasFd)) {
113
119
  addGuideline("Prefer grep/find/ls/rg/fd tools over bash for codebase exploration (faster and less noisy)");
114
120
  }
115
- if (hasRg || hasFd || hasAstGrep || hasComby || hasJq || hasYq || hasSemgrep || hasSed || hasSemanticSearch) {
116
- addGuideline("Route work to specialized tools first: rg/fd (search/discovery), semantic_search (concept-level retrieval), ast_grep/comby (structural code queries), jq/yq (data/config transforms), semgrep (risk scans), sed (stream extraction)");
121
+ if (hasBash && hasGitRead) {
122
+ addGuideline("Prefer git_read over bash for git status/diff/log/blame analysis in read-only workflows");
123
+ }
124
+ if (hasBash && hasFetch) {
125
+ addGuideline("Prefer fetch over bash curl/wget for HTTP retrieval when structured request parameters are sufficient");
126
+ }
127
+ if (hasRg || hasFd || hasAstGrep || hasComby || hasJq || hasYq || hasSemgrep || hasSed || hasSemanticSearch || hasFetch || hasGitRead || hasFsOps) {
128
+ addGuideline("Route work to specialized tools first: rg/fd (search/discovery), semantic_search (concept-level retrieval), ast_grep/comby (structural code queries), jq/yq (data/config transforms), semgrep (risk scans), sed (stream extraction), fetch (HTTP retrieval), git_read (git analysis), fs_ops (filesystem mutations)");
117
129
  }
118
130
  if (hasAstGrep || hasComby) {
119
131
  addGuideline("Use ast_grep/comby for syntax-aware structural queries before falling back to broad regex");
@@ -153,6 +165,9 @@ export function buildSystemPrompt(options = {}) {
153
165
  if (hasWrite) {
154
166
  addGuideline("Use write only for new files or complete rewrites");
155
167
  }
168
+ if (hasFsOps) {
169
+ addGuideline("Use fs_ops for mkdir/move/copy/delete workflows instead of broad bash file mutation commands");
170
+ }
156
171
  // Output guideline (only when actually writing or executing)
157
172
  if (hasEdit || hasWrite) {
158
173
  addGuideline("When summarizing your actions, output plain text directly - do NOT use cat or bash to display what you did");
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE,0CAA0C;AAC1C,MAAM,gBAAgB,GAA2B;IAChD,IAAI,EAAE,oBAAoB;IAC1B,IAAI,EAAE,8CAA8C;IACpD,IAAI,EAAE,4DAA4D;IAClE,KAAK,EAAE,2BAA2B;IAClC,IAAI,EAAE,yDAAyD;IAC/D,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M,IAAI,gCAAgC,WAAW,EAAE,CAAC;IAExD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\n\n/** Tool descriptions for system prompt */\nconst toolDescriptions: Record<string, string> = {\n\tread: \"Read file contents\",\n\tbash: \"Execute bash commands (ls, grep, find, etc.)\",\n\tedit: \"Make surgical edits to files (find exact text and replace)\",\n\twrite: \"Create or overwrite files\",\n\tgrep: \"Search file contents for patterns (respects .gitignore)\",\n\tfind: \"Find files by glob pattern (respects .gitignore)\",\n\tls: \"List directory contents\",\n\trg: \"Run ripgrep directly for advanced regex search (prefer explicit path args, e.g. -n pattern .)\",\n\tfd: \"Run fd directly for fast file discovery\",\n\tast_grep:\n\t\t\"Run ast-grep for AST/syntax-aware structural code search (prefer run --pattern; retry with scan/-p on older versions)\",\n\tcomby:\n\t\t\"Run comby for structural pattern search/rewrite previews (prefer explicit -matcher; no in-place edits)\",\n\tjq: \"Run jq for JSON querying/transformation\",\n\tyq: \"Run yq for YAML/JSON/TOML querying/transformation\",\n\tsemgrep: \"Run semgrep for structural/static security checks\",\n\tsed: \"Run sed for stream editing/extraction previews (no in-place edits)\",\n\tsemantic_search:\n\t\t\"Semantic embeddings search over the project index (actions: status, index, rebuild, query)\",\n\ttask: \"Run a specialized subagent (supports profile, cwd, lock_key for optional write serialization, run_id/task_id, model override, background mode for detached runs, and agent=<custom name from .iosm/agents>)\",\n};\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. Default: process.cwd() */\n\tcwd?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions = {}): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd ?? process.cwd();\n\n\tconst now = new Date();\n\tconst dateTime = now.toLocaleString(\"en-US\", {\n\t\tweekday: \"long\",\n\t\tyear: \"numeric\",\n\t\tmonth: \"long\",\n\t\tday: \"numeric\",\n\t\thour: \"2-digit\",\n\t\tminute: \"2-digit\",\n\t\tsecond: \"2-digit\",\n\t\ttimeZoneName: \"short\",\n\t});\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Add date/time and working directory last\n\t\tprompt += `\\nCurrent date and time: ${dateTime}`;\n\t\tprompt += `\\nCurrent working directory: ${resolvedCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// Built-ins use toolDescriptions. Custom tools can provide one-line snippets.\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst toolsList =\n\t\ttools.length > 0\n\t\t\t? tools\n\t\t\t\t\t.map((name) => {\n\t\t\t\t\t\tconst snippet = toolSnippets?.[name] ?? toolDescriptions[name] ?? name;\n\t\t\t\t\t\treturn `- ${name}: ${snippet}`;\n\t\t\t\t\t})\n\t\t\t\t\t.join(\"\\n\")\n\t\t\t: \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasEdit = tools.includes(\"edit\");\n\tconst hasWrite = tools.includes(\"write\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRg = tools.includes(\"rg\");\n\tconst hasFd = tools.includes(\"fd\");\n\tconst hasAstGrep = tools.includes(\"ast_grep\");\n\tconst hasComby = tools.includes(\"comby\");\n\tconst hasJq = tools.includes(\"jq\");\n\tconst hasYq = tools.includes(\"yq\");\n\tconst hasSemgrep = tools.includes(\"semgrep\");\n\tconst hasSed = tools.includes(\"sed\");\n\tconst hasSemanticSearch = tools.includes(\"semantic_search\");\n\tconst hasRead = tools.includes(\"read\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs && !hasRg && !hasFd) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find; prefer rg for targeted search when available\");\n\t} else if (hasBash && (hasGrep || hasFind || hasLs || hasRg || hasFd)) {\n\t\taddGuideline(\"Prefer grep/find/ls/rg/fd tools over bash for codebase exploration (faster and less noisy)\");\n\t}\n\n\tif (hasRg || hasFd || hasAstGrep || hasComby || hasJq || hasYq || hasSemgrep || hasSed || hasSemanticSearch) {\n\t\taddGuideline(\n\t\t\t\"Route work to specialized tools first: rg/fd (search/discovery), semantic_search (concept-level retrieval), ast_grep/comby (structural code queries), jq/yq (data/config transforms), semgrep (risk scans), sed (stream extraction)\",\n\t\t);\n\t}\n\n\tif (hasAstGrep || hasComby) {\n\t\taddGuideline(\"Use ast_grep/comby for syntax-aware structural queries before falling back to broad regex\");\n\t}\n\n\tif (hasComby) {\n\t\taddGuideline(\"Use comby to preview structural rewrite matches first, then apply final changes via edit/write\");\n\t}\n\n\tif (hasJq || hasYq) {\n\t\taddGuideline(\"Prefer jq/yq over ad-hoc shell parsing when extracting or transforming JSON/YAML/TOML\");\n\t}\n\n\tif (hasSemgrep) {\n\t\taddGuideline(\"Use semgrep for rule-based risk scans and structural security checks when relevant\");\n\t}\n\n\tif (hasSed) {\n\t\taddGuideline(\"Use sed for preview/extraction workflows only; perform final file edits with edit/write\");\n\t}\n\n\tif (hasSemanticSearch) {\n\t\taddGuideline(\n\t\t\t\"Use semantic_search for intent/meaning queries that are hard to express with regex; use rg/ast_grep for exact symbol and syntax matches\",\n\t\t);\n\t\taddGuideline(\n\t\t\t\"semantic_search query can auto-refresh stale indexes when semantic auto-index is enabled (default); if disabled or if provider/chunk/filter changes require it, run semantic_search index/rebuild explicitly\",\n\t\t);\n\t}\n\n\tif (hasRg || hasAstGrep || hasComby) {\n\t\taddGuideline(\n\t\t\t\"For rg/ast_grep/comby, pass explicit target paths to avoid cwd ambiguity; if syntax errors occur (especially ast_grep), retry once with version-compatible command forms before concluding no matches\",\n\t\t);\n\t}\n\n\tif (\n\t\thasBash &&\n\t\t(hasRg || hasFd || hasAstGrep || hasComby || hasJq || hasYq || hasSemgrep || hasSed || hasSemanticSearch)\n\t) {\n\t\taddGuideline(\n\t\t\t\"If a required CLI tool is missing, install it first when permitted (rg/fd can be auto-managed; others via brew/apt/pipx/npm), then continue with that tool instead of broad bash fallback. For semantic_search, configure provider/index first via /semantic setup.\",\n\t\t);\n\t}\n\n\t// Read before edit guideline\n\tif (hasRead && hasEdit) {\n\t\taddGuideline(\"Use read to examine files before editing. You must use this tool instead of cat or sed.\");\n\t}\n\n\t// Edit guideline\n\tif (hasEdit) {\n\t\taddGuideline(\"Use edit for precise changes (old text must match exactly)\");\n\t}\n\n\t// Write guideline\n\tif (hasWrite) {\n\t\taddGuideline(\"Use write only for new files or complete rewrites\");\n\t}\n\n\t// Output guideline (only when actually writing or executing)\n\tif (hasEdit || hasWrite) {\n\t\taddGuideline(\n\t\t\t\"When summarizing your actions, output plain text directly - do NOT use cat or bash to display what you did\",\n\t\t);\n\t}\n\n\taddGuideline(\"Inspect the relevant files before editing and keep exploration bounded to the task\");\n\taddGuideline(\"Make reasonable assumptions and continue unless a risky ambiguity blocks the work\");\n\taddGuideline(\"Classify requests as simple vs complex: execute simple work immediately, use a step plan for complex work\");\n\taddGuideline(\"For complex work, publish a short step plan before edits and keep step statuses current while executing\");\n\taddGuideline(\"If a meaningful architecture or product fork changes implementation, ask a concise clarification before editing\");\n\taddGuideline(\"After changes, run the smallest relevant verification and report the concrete result\");\n\taddGuideline(\"Do not claim success without evidence; if you could not verify, say so explicitly\");\n\taddGuideline(\"Complete the requested task end-to-end when possible instead of stopping at analysis\");\n\taddGuideline(\"For code review requests, lead with findings and risks before summaries\");\n\taddGuideline(\n\t\t\"When an active engineering contract is present in context, treat its constraints, quality gates, and definition_of_done as execution requirements unless user overrides them.\",\n\t);\n\taddGuideline(\"For major feature forks, run a /singular feasibility pass before coding to compare implementation options.\");\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are a professional software engineering agent operating inside iosm-cli. Help users inspect systems, change code, run commands, maintain project artifacts when needed, and explain results clearly.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nOperating defaults:\n- Summarize work in standard engineering language first: what you inspected, what you changed, what you verified, and any remaining risk or blocker.\n- Do NOT start by reading documentation unless the user asks for documentation help, asks about harness internals, or implementation is blocked without it.\n- Start implementation turns with a quick repository scan of the files most likely to matter before proposing or editing.\n- Prefer targeted reads and searches over broad dumps; keep command output bounded and focused.\n- For complex tasks, include a machine-readable plan block before edits and update it when statuses change:\n <task_plan complexity=\"complex\">\n - [in_progress] Current step\n - [pending] Next step\n </task_plan>\n- Skip plan blocks for simple one-shot tasks.\n- When a material architecture fork exists, pause and ask one concise clarification (or use ask_user when available) before implementation.\n- Treat verification as mandatory after edits: tests, type checks, linters, or a precise explanation of why verification was not possible.\n- For complex requests, execute plan steps in order, close each step explicitly, and finish the full plan unless blocked.\n- If the user explicitly asks for subagents/agents orchestration, you MUST use the task tool rather than doing all work in the main agent.\n- For explicit subagent/orchestration requests, execute at least one task tool call before giving a final prose-only answer.\n- Do not expose internal orchestration scaffolding to the user (for example: [ORCHESTRATION_DIRECTIVE], pseudo tool-call JSON, or raw task arguments).\n- When invoking tools, call them directly without preambles like \"I will now call tool X\"; only report outcomes that matter to the user.\n\t- Respect orchestration constraints from the user exactly: count, parallel vs sequential execution, per-agent profile, and per-agent working directory (cwd) when provided.\n\t- Treat explicit orchestration requests in any language as constraints (including non-English text and minor typos).\n\t- For explicit parallel orchestration requests, issue multiple independent task tool calls to match the requested agent count; do not collapse to a single subagent unless the user asks for one.\n- For explicit parallel orchestration requests, emit independent task calls in a single assistant turn whenever possible so they can be launched together.\n- Runtime note: when parallel orchestration is requested, emit independent task calls in one assistant turn so they can run concurrently; avoid background mode unless the user explicitly asks for detached async runs.\n- If orchestration constraints are ambiguous or conflict, ask one concise clarification (or use ask_user when available) before launching subagents.\n- When the user provides an <orchestrate ...>...</orchestrate> block, treat it as an execution contract and follow its mode/agents/profile/cwd assignments strictly.\n- When orchestration assignments include run_id/task_id/lock_key or depends_on, enforce them in task calls (run_id/task_id for team tracking, lock_key for serialization domains, depends_on for ordering).\n- For delegated parallel runs, use shared_memory_* tools as the primary coordination channel: namespaced keys, read-before-write, and CAS (if_version) for contested updates; reserve append mode for timeline/log keys.\n- For write-heavy parallel orchestration, prefer isolation=worktree to reduce cross-agent interference when the repository is git-backed.\n- If the user message includes @<custom-agent-name>, treat it as an explicit agent selection and call task with agent set to that custom agent name.\n\niosm-cli reference docs (use when needed):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), package composition (docs/packages.md)\n- When working on harness internals, read the relevant docs/examples before implementing`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Add date/time and working directory last\n\tprompt += `\\nCurrent date and time: ${dateTime}`;\n\tprompt += `\\nCurrent working directory: ${resolvedCwd}`;\n\n\treturn prompt;\n}\n"]}
1
+ {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE,0CAA0C;AAC1C,MAAM,gBAAgB,GAA2B;IAChD,IAAI,EAAE,oBAAoB;IAC1B,IAAI,EAAE,8CAA8C;IACpD,IAAI,EAAE,4DAA4D;IAClE,KAAK,EAAE,2BAA2B;IAClC,IAAI,EAAE,yDAAyD;IAC/D,IAAI,EAAE,kDAAkD;IACxD,EAAE,EAAE,yBAAyB;IAC7B,EAAE,EAAE,+FAA+F;IACnG,EAAE,EAAE,yCAAyC;IAC7C,QAAQ,EACP,uHAAuH;IACxH,KAAK,EACJ,wGAAwG;IACzG,EAAE,EAAE,yCAAyC;IAC7C,EAAE,EAAE,mDAAmD;IACvD,OAAO,EAAE,mDAAmD;IAC5D,GAAG,EAAE,oEAAoE;IACzE,eAAe,EACd,4FAA4F;IAC7F,KAAK,EAAE,+EAA+E;IACtF,QAAQ,EAAE,mEAAmE;IAC7E,MAAM,EAAE,yFAAyF;IACjG,IAAI,EAAE,6MAA6M;CACnN,CAAC;AAqBF,kEAAkE;AAClE,MAAM,UAAU,iBAAiB,CAAC,UAAoC,EAAE;IACvE,MAAM,EACL,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,GAAG,EACH,YAAY,EAAE,oBAAoB,EAClC,MAAM,EAAE,cAAc,GACtB,GAAG,OAAO,CAAC;IACZ,MAAM,WAAW,GAAG,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;IAEzC,MAAM,GAAG,GAAG,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getReadmePath } from \"../config.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\n\n/** Tool descriptions for system prompt */\nconst toolDescriptions: Record<string, string> = {\n\tread: \"Read file contents\",\n\tbash: \"Execute bash commands (ls, grep, find, etc.)\",\n\tedit: \"Make surgical edits to files (find exact text and replace)\",\n\twrite: \"Create or overwrite files\",\n\tgrep: \"Search file contents for patterns (respects .gitignore)\",\n\tfind: \"Find files by glob pattern (respects .gitignore)\",\n\tls: \"List directory contents\",\n\trg: \"Run ripgrep directly for advanced regex search (prefer explicit path args, e.g. -n pattern .)\",\n\tfd: \"Run fd directly for fast file discovery\",\n\tast_grep:\n\t\t\"Run ast-grep for AST/syntax-aware structural code search (prefer run --pattern; retry with scan/-p on older versions)\",\n\tcomby:\n\t\t\"Run comby for structural pattern search/rewrite previews (prefer explicit -matcher; no in-place edits)\",\n\tjq: \"Run jq for JSON querying/transformation\",\n\tyq: \"Run yq for YAML/JSON/TOML querying/transformation\",\n\tsemgrep: \"Run semgrep for structural/static security checks\",\n\tsed: \"Run sed for stream editing/extraction previews (no in-place edits)\",\n\tsemantic_search:\n\t\t\"Semantic embeddings search over the project index (actions: status, index, rebuild, query)\",\n\tfetch: \"Make HTTP requests with bounded response capture and manual redirect handling\",\n\tgit_read: \"Structured read-only git introspection (status, diff, log, blame)\",\n\tfs_ops: \"Structured filesystem mutations (mkdir, move, copy, delete) with recursive/force guards\",\n\ttask: \"Run a specialized subagent (supports profile, cwd, lock_key for optional write serialization, run_id/task_id, model override, background mode for detached runs, and agent=<custom name from .iosm/agents>)\",\n};\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. Default: process.cwd() */\n\tcwd?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions = {}): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd ?? process.cwd();\n\n\tconst now = new Date();\n\tconst dateTime = now.toLocaleString(\"en-US\", {\n\t\tweekday: \"long\",\n\t\tyear: \"numeric\",\n\t\tmonth: \"long\",\n\t\tday: \"numeric\",\n\t\thour: \"2-digit\",\n\t\tminute: \"2-digit\",\n\t\tsecond: \"2-digit\",\n\t\ttimeZoneName: \"short\",\n\t});\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Add date/time and working directory last\n\t\tprompt += `\\nCurrent date and time: ${dateTime}`;\n\t\tprompt += `\\nCurrent working directory: ${resolvedCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// Built-ins use toolDescriptions. Custom tools can provide one-line snippets.\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst toolsList =\n\t\ttools.length > 0\n\t\t\t? tools\n\t\t\t\t\t.map((name) => {\n\t\t\t\t\t\tconst snippet = toolSnippets?.[name] ?? toolDescriptions[name] ?? name;\n\t\t\t\t\t\treturn `- ${name}: ${snippet}`;\n\t\t\t\t\t})\n\t\t\t\t\t.join(\"\\n\")\n\t\t\t: \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasEdit = tools.includes(\"edit\");\n\tconst hasWrite = tools.includes(\"write\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRg = tools.includes(\"rg\");\n\tconst hasFd = tools.includes(\"fd\");\n\tconst hasAstGrep = tools.includes(\"ast_grep\");\n\tconst hasComby = tools.includes(\"comby\");\n\tconst hasJq = tools.includes(\"jq\");\n\tconst hasYq = tools.includes(\"yq\");\n\tconst hasSemgrep = tools.includes(\"semgrep\");\n\tconst hasSed = tools.includes(\"sed\");\n\tconst hasSemanticSearch = tools.includes(\"semantic_search\");\n\tconst hasFetch = tools.includes(\"fetch\");\n\tconst hasGitRead = tools.includes(\"git_read\");\n\tconst hasFsOps = tools.includes(\"fs_ops\");\n\tconst hasRead = tools.includes(\"read\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs && !hasRg && !hasFd) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find; prefer rg for targeted search when available\");\n\t} else if (hasBash && (hasGrep || hasFind || hasLs || hasRg || hasFd)) {\n\t\taddGuideline(\"Prefer grep/find/ls/rg/fd tools over bash for codebase exploration (faster and less noisy)\");\n\t}\n\tif (hasBash && hasGitRead) {\n\t\taddGuideline(\"Prefer git_read over bash for git status/diff/log/blame analysis in read-only workflows\");\n\t}\n\tif (hasBash && hasFetch) {\n\t\taddGuideline(\"Prefer fetch over bash curl/wget for HTTP retrieval when structured request parameters are sufficient\");\n\t}\n\n\tif (hasRg || hasFd || hasAstGrep || hasComby || hasJq || hasYq || hasSemgrep || hasSed || hasSemanticSearch || hasFetch || hasGitRead || hasFsOps) {\n\t\taddGuideline(\n\t\t\t\"Route work to specialized tools first: rg/fd (search/discovery), semantic_search (concept-level retrieval), ast_grep/comby (structural code queries), jq/yq (data/config transforms), semgrep (risk scans), sed (stream extraction), fetch (HTTP retrieval), git_read (git analysis), fs_ops (filesystem mutations)\",\n\t\t);\n\t}\n\n\tif (hasAstGrep || hasComby) {\n\t\taddGuideline(\"Use ast_grep/comby for syntax-aware structural queries before falling back to broad regex\");\n\t}\n\n\tif (hasComby) {\n\t\taddGuideline(\"Use comby to preview structural rewrite matches first, then apply final changes via edit/write\");\n\t}\n\n\tif (hasJq || hasYq) {\n\t\taddGuideline(\"Prefer jq/yq over ad-hoc shell parsing when extracting or transforming JSON/YAML/TOML\");\n\t}\n\n\tif (hasSemgrep) {\n\t\taddGuideline(\"Use semgrep for rule-based risk scans and structural security checks when relevant\");\n\t}\n\n\tif (hasSed) {\n\t\taddGuideline(\"Use sed for preview/extraction workflows only; perform final file edits with edit/write\");\n\t}\n\n\tif (hasSemanticSearch) {\n\t\taddGuideline(\n\t\t\t\"Use semantic_search for intent/meaning queries that are hard to express with regex; use rg/ast_grep for exact symbol and syntax matches\",\n\t\t);\n\t\taddGuideline(\n\t\t\t\"semantic_search query can auto-refresh stale indexes when semantic auto-index is enabled (default); if disabled or if provider/chunk/filter changes require it, run semantic_search index/rebuild explicitly\",\n\t\t);\n\t}\n\n\tif (hasRg || hasAstGrep || hasComby) {\n\t\taddGuideline(\n\t\t\t\"For rg/ast_grep/comby, pass explicit target paths to avoid cwd ambiguity; if syntax errors occur (especially ast_grep), retry once with version-compatible command forms before concluding no matches\",\n\t\t);\n\t}\n\n\tif (\n\t\thasBash &&\n\t\t(hasRg || hasFd || hasAstGrep || hasComby || hasJq || hasYq || hasSemgrep || hasSed || hasSemanticSearch)\n\t) {\n\t\taddGuideline(\n\t\t\t\"If a required CLI tool is missing, install it first when permitted (rg/fd can be auto-managed; others via brew/apt/pipx/npm), then continue with that tool instead of broad bash fallback. For semantic_search, configure provider/index first via /semantic setup.\",\n\t\t);\n\t}\n\n\t// Read before edit guideline\n\tif (hasRead && hasEdit) {\n\t\taddGuideline(\"Use read to examine files before editing. You must use this tool instead of cat or sed.\");\n\t}\n\n\t// Edit guideline\n\tif (hasEdit) {\n\t\taddGuideline(\"Use edit for precise changes (old text must match exactly)\");\n\t}\n\n\t// Write guideline\n\tif (hasWrite) {\n\t\taddGuideline(\"Use write only for new files or complete rewrites\");\n\t}\n\tif (hasFsOps) {\n\t\taddGuideline(\"Use fs_ops for mkdir/move/copy/delete workflows instead of broad bash file mutation commands\");\n\t}\n\n\t// Output guideline (only when actually writing or executing)\n\tif (hasEdit || hasWrite) {\n\t\taddGuideline(\n\t\t\t\"When summarizing your actions, output plain text directly - do NOT use cat or bash to display what you did\",\n\t\t);\n\t}\n\n\taddGuideline(\"Inspect the relevant files before editing and keep exploration bounded to the task\");\n\taddGuideline(\"Make reasonable assumptions and continue unless a risky ambiguity blocks the work\");\n\taddGuideline(\"Classify requests as simple vs complex: execute simple work immediately, use a step plan for complex work\");\n\taddGuideline(\"For complex work, publish a short step plan before edits and keep step statuses current while executing\");\n\taddGuideline(\"If a meaningful architecture or product fork changes implementation, ask a concise clarification before editing\");\n\taddGuideline(\"After changes, run the smallest relevant verification and report the concrete result\");\n\taddGuideline(\"Do not claim success without evidence; if you could not verify, say so explicitly\");\n\taddGuideline(\"Complete the requested task end-to-end when possible instead of stopping at analysis\");\n\taddGuideline(\"For code review requests, lead with findings and risks before summaries\");\n\taddGuideline(\n\t\t\"When an active engineering contract is present in context, treat its constraints, quality gates, and definition_of_done as execution requirements unless user overrides them.\",\n\t);\n\taddGuideline(\"For major feature forks, run a /singular feasibility pass before coding to compare implementation options.\");\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are a professional software engineering agent operating inside iosm-cli. Help users inspect systems, change code, run commands, maintain project artifacts when needed, and explain results clearly.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nOperating defaults:\n- Summarize work in standard engineering language first: what you inspected, what you changed, what you verified, and any remaining risk or blocker.\n- Do NOT start by reading documentation unless the user asks for documentation help, asks about harness internals, or implementation is blocked without it.\n- Start implementation turns with a quick repository scan of the files most likely to matter before proposing or editing.\n- Prefer targeted reads and searches over broad dumps; keep command output bounded and focused.\n- For complex tasks, include a machine-readable plan block before edits and update it when statuses change:\n <task_plan complexity=\"complex\">\n - [in_progress] Current step\n - [pending] Next step\n </task_plan>\n- Skip plan blocks for simple one-shot tasks.\n- When a material architecture fork exists, pause and ask one concise clarification (or use ask_user when available) before implementation.\n- Treat verification as mandatory after edits: tests, type checks, linters, or a precise explanation of why verification was not possible.\n- For complex requests, execute plan steps in order, close each step explicitly, and finish the full plan unless blocked.\n- If the user explicitly asks for subagents/agents orchestration, you MUST use the task tool rather than doing all work in the main agent.\n- For explicit subagent/orchestration requests, execute at least one task tool call before giving a final prose-only answer.\n- Do not expose internal orchestration scaffolding to the user (for example: [ORCHESTRATION_DIRECTIVE], pseudo tool-call JSON, or raw task arguments).\n- When invoking tools, call them directly without preambles like \"I will now call tool X\"; only report outcomes that matter to the user.\n\t- Respect orchestration constraints from the user exactly: count, parallel vs sequential execution, per-agent profile, and per-agent working directory (cwd) when provided.\n\t- Treat explicit orchestration requests in any language as constraints (including non-English text and minor typos).\n\t- For explicit parallel orchestration requests, issue multiple independent task tool calls to match the requested agent count; do not collapse to a single subagent unless the user asks for one.\n- For explicit parallel orchestration requests, emit independent task calls in a single assistant turn whenever possible so they can be launched together.\n- Runtime note: when parallel orchestration is requested, emit independent task calls in one assistant turn so they can run concurrently; avoid background mode unless the user explicitly asks for detached async runs.\n- If orchestration constraints are ambiguous or conflict, ask one concise clarification (or use ask_user when available) before launching subagents.\n- When the user provides an <orchestrate ...>...</orchestrate> block, treat it as an execution contract and follow its mode/agents/profile/cwd assignments strictly.\n- When orchestration assignments include run_id/task_id/lock_key or depends_on, enforce them in task calls (run_id/task_id for team tracking, lock_key for serialization domains, depends_on for ordering).\n- For delegated parallel runs, use shared_memory_* tools as the primary coordination channel: namespaced keys, read-before-write, and CAS (if_version) for contested updates; reserve append mode for timeline/log keys.\n- For write-heavy parallel orchestration, prefer isolation=worktree to reduce cross-agent interference when the repository is git-backed.\n- If the user message includes @<custom-agent-name>, treat it as an explicit agent selection and call task with agent set to that custom agent name.\n\niosm-cli reference docs (use when needed):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), package composition (docs/packages.md)\n- When working on harness internals, read the relevant docs/examples before implementing`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Add date/time and working directory last\n\tprompt += `\\nCurrent date and time: ${dateTime}`;\n\tprompt += `\\nCurrent working directory: ${resolvedCwd}`;\n\n\treturn prompt;\n}\n"]}
@@ -0,0 +1,56 @@
1
+ import type { AgentTool } from "@mariozechner/pi-agent-core";
2
+ import { type Static } from "@sinclair/typebox";
3
+ import type { ToolPermissionGuard } from "./permissions.js";
4
+ import { type TruncationResult } from "./truncate.js";
5
+ declare const fetchSchema: import("@sinclair/typebox").TObject<{
6
+ url: import("@sinclair/typebox").TString;
7
+ method: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"GET">, import("@sinclair/typebox").TLiteral<"POST">, import("@sinclair/typebox").TLiteral<"PUT">, import("@sinclair/typebox").TLiteral<"PATCH">, import("@sinclair/typebox").TLiteral<"DELETE">, import("@sinclair/typebox").TLiteral<"HEAD">, import("@sinclair/typebox").TLiteral<"OPTIONS">]>>;
8
+ headers: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TRecord<import("@sinclair/typebox").TString, import("@sinclair/typebox").TString>>;
9
+ body: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
10
+ timeout: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
11
+ max_bytes: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
12
+ response_format: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"auto">, import("@sinclair/typebox").TLiteral<"json">, import("@sinclair/typebox").TLiteral<"text">]>>;
13
+ max_redirects: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
14
+ }>;
15
+ export type FetchToolInput = Static<typeof fetchSchema>;
16
+ export type FetchResponseFormat = "auto" | "json" | "text";
17
+ export type FetchMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
18
+ export declare const DEFAULT_FETCH_TIMEOUT_SECONDS = 30;
19
+ export declare const DEFAULT_FETCH_MAX_BYTES: number;
20
+ export declare const DEFAULT_FETCH_MAX_REDIRECTS = 5;
21
+ export interface FetchToolDetails {
22
+ method: FetchMethod;
23
+ requestUrl: string;
24
+ finalUrl: string;
25
+ status: number;
26
+ statusText: string;
27
+ redirectsFollowed: number;
28
+ responseFormat: "json" | "text";
29
+ timeoutSeconds: number;
30
+ maxBytes: number;
31
+ bodyBytesCaptured: number;
32
+ bodyCaptureTruncated: boolean;
33
+ truncation?: TruncationResult;
34
+ }
35
+ export interface FetchToolOptions {
36
+ fetchImpl?: typeof fetch;
37
+ permissionGuard?: ToolPermissionGuard;
38
+ resolveAllowedMethods?: () => ReadonlySet<FetchMethod> | readonly FetchMethod[];
39
+ defaultTimeoutSeconds?: number;
40
+ defaultMaxBytes?: number;
41
+ defaultMaxRedirects?: number;
42
+ }
43
+ export declare function getAllowedFetchMethodsForProfile(profileName: string | undefined): ReadonlySet<FetchMethod>;
44
+ export declare function createFetchTool(cwd: string, options?: FetchToolOptions): AgentTool<typeof fetchSchema>;
45
+ export declare const fetchTool: AgentTool<import("@sinclair/typebox").TObject<{
46
+ url: import("@sinclair/typebox").TString;
47
+ method: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"GET">, import("@sinclair/typebox").TLiteral<"POST">, import("@sinclair/typebox").TLiteral<"PUT">, import("@sinclair/typebox").TLiteral<"PATCH">, import("@sinclair/typebox").TLiteral<"DELETE">, import("@sinclair/typebox").TLiteral<"HEAD">, import("@sinclair/typebox").TLiteral<"OPTIONS">]>>;
48
+ headers: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TRecord<import("@sinclair/typebox").TString, import("@sinclair/typebox").TString>>;
49
+ body: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
50
+ timeout: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
51
+ max_bytes: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
52
+ response_format: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"auto">, import("@sinclair/typebox").TLiteral<"json">, import("@sinclair/typebox").TLiteral<"text">]>>;
53
+ max_redirects: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
54
+ }>, any>;
55
+ export {};
56
+ //# sourceMappingURL=fetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/core/tools/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,KAAK,MAAM,EAAQ,MAAM,mBAAmB,CAAC;AAEtD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAIN,KAAK,gBAAgB,EAErB,MAAM,eAAe,CAAC;AAEvB,QAAA,MAAM,WAAW;;;;;;;;;EAsCf,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AACxD,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;AAC3D,MAAM,MAAM,WAAW,GAAG,KAAK,GAAG,MAAM,GAA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