@caupulican/pi-adaptative 0.81.13 → 0.81.16

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 (55) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/bundled-resources/runtimes/hf-transformers-openai-server.py +427 -0
  3. package/dist/bundled-resources/skills/tool-call-repair/SKILL.md +13 -11
  4. package/dist/bundled-resources/skills/tool-call-repair/references/failure-grammar.md +16 -10
  5. package/dist/bundled-resources/skills/tool-call-repair/references/text-protocol-grammar.md +14 -7
  6. package/dist/core/agent-session.d.ts +11 -3
  7. package/dist/core/agent-session.d.ts.map +1 -1
  8. package/dist/core/agent-session.js +132 -23
  9. package/dist/core/agent-session.js.map +1 -1
  10. package/dist/core/local-runtime-controller.d.ts +17 -9
  11. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  12. package/dist/core/local-runtime-controller.js +124 -20
  13. package/dist/core/local-runtime-controller.js.map +1 -1
  14. package/dist/core/models/adaptation-store.d.ts +2 -0
  15. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  16. package/dist/core/models/adaptation-store.js +4 -0
  17. package/dist/core/models/adaptation-store.js.map +1 -1
  18. package/dist/core/models/default-model-suggestions.d.ts +4 -4
  19. package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
  20. package/dist/core/models/default-model-suggestions.js +9 -0
  21. package/dist/core/models/default-model-suggestions.js.map +1 -1
  22. package/dist/core/models/local-registration.d.ts +12 -0
  23. package/dist/core/models/local-registration.d.ts.map +1 -1
  24. package/dist/core/models/local-registration.js +68 -0
  25. package/dist/core/models/local-registration.js.map +1 -1
  26. package/dist/core/models/local-runtime.d.ts +77 -1
  27. package/dist/core/models/local-runtime.d.ts.map +1 -1
  28. package/dist/core/models/local-runtime.js +295 -4
  29. package/dist/core/models/local-runtime.js.map +1 -1
  30. package/dist/core/models/model-ref.d.ts +4 -0
  31. package/dist/core/models/model-ref.d.ts.map +1 -1
  32. package/dist/core/models/model-ref.js +12 -3
  33. package/dist/core/models/model-ref.js.map +1 -1
  34. package/dist/core/tool-repair-health.d.ts.map +1 -1
  35. package/dist/core/tool-repair-health.js +2 -1
  36. package/dist/core/tool-repair-health.js.map +1 -1
  37. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  38. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  39. package/dist/modes/interactive/interactive-mode.js +4 -0
  40. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  41. package/dist/modes/interactive/local-model-commands.d.ts +3 -1
  42. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  43. package/dist/modes/interactive/local-model-commands.js +133 -19
  44. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  45. package/docs/models.md +19 -1
  46. package/docs/tool-repair.md +2 -0
  47. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  48. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  49. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  50. package/examples/extensions/sandbox/package-lock.json +2 -2
  51. package/examples/extensions/sandbox/package.json +1 -1
  52. package/examples/extensions/with-deps/package-lock.json +2 -2
  53. package/examples/extensions/with-deps/package.json +1 -1
  54. package/npm-shrinkwrap.json +12 -12
  55. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"adaptation-store.js","sourceRoot":"","sources":["../../../src/core/models/adaptation-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAwB,MAAM,oBAAoB,CAAC;AAElF,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAC9B,MAAM,eAAe,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GA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CAC9F,CAAC;IAAA,CACF;CACD","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { currentHostFingerprint, type HostFingerprint } from \"./fitness-store.ts\";\n\nconst STORE_VERSION = 1;\nconst MAX_RULES_PER_MODEL = 5;\nconst RETIRE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;\n\nexport interface ModelAdaptationRule {\n\tmode: string;\n\ttext: string;\n\taddedAt: string;\n\tlastFiredAt: string;\n}\n\nexport type ModelProtocolCalibration =\n\t| {\n\t\t\tversion: number;\n\t\t\tstatus?: \"calibrated\";\n\t\t\tvariant: string;\n\t\t\tcalibratedAt: string;\n\t }\n\t| {\n\t\t\tversion: number;\n\t\t\tstatus: \"failed\";\n\t\t\tattemptedAt: string;\n\t\t\tvariantsTried: string[];\n\t };\n\nexport type ModelToolProbeVerdict = \"native\" | \"text-protocol\" | \"none\";\n\nexport interface ModelToolProbe {\n\tversion: number;\n\tstatus: ModelToolProbeVerdict;\n\tprobedAt: string;\n\tvariant?: string;\n\tdiagnostic?: string;\n}\n\nexport interface ModelTeachStats {\n\ttaught: number;\n\trecurrenceBefore: number;\n\trecurrenceAfter: number;\n}\n\nexport interface ModelAdaptationProfile {\n\trules: ModelAdaptationRule[];\n\tprotocol?: ModelProtocolCalibration;\n\ttoolProbe?: ModelToolProbe;\n\tteachStats: Record<string, ModelTeachStats>;\n}\n\nexport interface StoredModelAdaptation {\n\tmodel: string;\n\tprofile: ModelAdaptationProfile;\n\tat: string;\n\thost: HostFingerprint;\n}\n\ninterface AdaptationStoreFile {\n\tversion: 1;\n\t/** hostId -> modelRef -> latest stored adaptation profile. */\n\thosts: Record<string, Record<string, StoredModelAdaptation>>;\n}\n\nfunction emptyProfile(): ModelAdaptationProfile {\n\treturn { rules: [], teachStats: {} };\n}\n\nfunction normalizeProfile(profile: Partial<ModelAdaptationProfile> | undefined): ModelAdaptationProfile {\n\treturn {\n\t\trules: Array.isArray(profile?.rules) ? profile.rules.filter(isRule) : [],\n\t\t...(isProtocol(profile?.protocol) && { protocol: profile.protocol }),\n\t\t...(isToolProbe(profile?.toolProbe) && { toolProbe: profile.toolProbe }),\n\t\tteachStats: isRecord(profile?.teachStats) ? filterTeachStats(profile.teachStats) : {},\n\t};\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isRule(value: unknown): value is ModelAdaptationRule {\n\treturn (\n\t\tisRecord(value) &&\n\t\ttypeof value.mode === \"string\" &&\n\t\ttypeof value.text === \"string\" &&\n\t\ttypeof value.addedAt === \"string\" &&\n\t\ttypeof value.lastFiredAt === \"string\"\n\t);\n}\n\nfunction isProtocol(value: unknown): value is ModelProtocolCalibration {\n\tif (!isRecord(value) || typeof value.version !== \"number\") return false;\n\tif (value.status === \"failed\") {\n\t\treturn (\n\t\t\ttypeof value.attemptedAt === \"string\" &&\n\t\t\tArray.isArray(value.variantsTried) &&\n\t\t\tvalue.variantsTried.every((variant) => typeof variant === \"string\")\n\t\t);\n\t}\n\treturn (\n\t\t(value.status === undefined || value.status === \"calibrated\") &&\n\t\ttypeof value.variant === \"string\" &&\n\t\ttypeof value.calibratedAt === \"string\"\n\t);\n}\n\nfunction isToolProbe(value: unknown): value is ModelToolProbe {\n\treturn (\n\t\tisRecord(value) &&\n\t\ttypeof value.version === \"number\" &&\n\t\t(value.status === \"native\" || value.status === \"text-protocol\" || value.status === \"none\") &&\n\t\ttypeof value.probedAt === \"string\" &&\n\t\t(value.variant === undefined || typeof value.variant === \"string\") &&\n\t\t(value.diagnostic === undefined || typeof value.diagnostic === \"string\")\n\t);\n}\n\nfunction isTeachStats(value: unknown): value is ModelTeachStats {\n\treturn (\n\t\tisRecord(value) &&\n\t\ttypeof value.taught === \"number\" &&\n\t\ttypeof value.recurrenceBefore === \"number\" &&\n\t\ttypeof value.recurrenceAfter === \"number\"\n\t);\n}\n\nfunction filterTeachStats(value: Record<string, unknown>): Record<string, ModelTeachStats> {\n\treturn Object.fromEntries(\n\t\tObject.entries(value).filter((entry): entry is [string, ModelTeachStats] => isTeachStats(entry[1])),\n\t);\n}\n\nfunction ruleRecency(rule: ModelAdaptationRule): number {\n\tconst lastFired = Date.parse(rule.lastFiredAt);\n\tif (Number.isFinite(lastFired)) return lastFired;\n\tconst added = Date.parse(rule.addedAt);\n\treturn Number.isFinite(added) ? added : 0;\n}\n\nfunction pruneRetiredRules(rules: readonly ModelAdaptationRule[], now: Date): ModelAdaptationRule[] {\n\tconst cutoff = now.getTime() - RETIRE_AFTER_MS;\n\treturn rules.filter((rule) => ruleRecency(rule) >= cutoff);\n}\n\nfunction enforceRuleCap(rules: readonly ModelAdaptationRule[]): ModelAdaptationRule[] {\n\tif (rules.length <= MAX_RULES_PER_MODEL) return [...rules];\n\treturn [...rules].sort((a, b) => ruleRecency(b) - ruleRecency(a)).slice(0, MAX_RULES_PER_MODEL);\n}\n\nfunction mergeRule(rules: readonly ModelAdaptationRule[], rule: ModelAdaptationRule): ModelAdaptationRule[] {\n\tconst withoutSameMode = rules.filter((existing) => existing.mode !== rule.mode);\n\treturn enforceRuleCap([...withoutSameMode, rule]);\n}\n\nexport class ModelAdaptationStore {\n\tprivate readonly filePath: string;\n\tprivate readonly fingerprint: () => HostFingerprint;\n\n\tconstructor(filePath: string, options?: { fingerprint?: () => HostFingerprint }) {\n\t\tthis.filePath = filePath;\n\t\tthis.fingerprint = options?.fingerprint ?? currentHostFingerprint;\n\t}\n\n\tstatic forAgentDir(agentDir: string, options?: { fingerprint?: () => HostFingerprint }): ModelAdaptationStore {\n\t\treturn new ModelAdaptationStore(join(agentDir, \"state\", \"model-adaptation.json\"), options);\n\t}\n\n\tprivate load(): AdaptationStoreFile {\n\t\ttry {\n\t\t\tif (!existsSync(this.filePath)) return { version: STORE_VERSION, hosts: {} };\n\t\t\tconst parsed = JSON.parse(readFileSync(this.filePath, \"utf-8\")) as AdaptationStoreFile;\n\t\t\tif (parsed && parsed.version === STORE_VERSION && parsed.hosts && typeof parsed.hosts === \"object\") {\n\t\t\t\treturn parsed;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Unreadable/corrupt store: start fresh in memory; the next save rewrites the file.\n\t\t}\n\t\treturn { version: STORE_VERSION, hosts: {} };\n\t}\n\n\tprivate write(file: AdaptationStoreFile): void {\n\t\tmkdirSync(dirname(this.filePath), { recursive: true });\n\t\twriteFileSync(this.filePath, `${JSON.stringify(file, null, \"\\t\")}\\n`, \"utf-8\");\n\t}\n\n\tprivate store(model: string, profile: ModelAdaptationProfile, at: string): StoredModelAdaptation {\n\t\tconst host = this.fingerprint();\n\t\tconst entry: StoredModelAdaptation = { model, profile: normalizeProfile(profile), at, host };\n\t\tconst file = this.load();\n\t\tfile.hosts[host.id] = { ...(file.hosts[host.id] ?? {}), [model]: entry };\n\t\tthis.write(file);\n\t\treturn entry;\n\t}\n\n\t/** Persist the profile for a model on the CURRENT host. Best-effort, returns the entry. */\n\tsave(model: string, profile: ModelAdaptationProfile, at?: string): StoredModelAdaptation {\n\t\treturn this.store(model, profile, at ?? new Date().toISOString());\n\t}\n\n\t/** Profile for a model on the current host; prunes retired rules before returning. */\n\tget(model: string, now: Date = new Date()): ModelAdaptationProfile {\n\t\tconst host = this.fingerprint();\n\t\tconst file = this.load();\n\t\tconst entry = file.hosts[host.id]?.[model];\n\t\tif (!entry) return emptyProfile();\n\t\tconst profile = normalizeProfile(entry.profile);\n\t\tconst prunedRules = pruneRetiredRules(profile.rules, now);\n\t\tif (prunedRules.length !== profile.rules.length) {\n\t\t\treturn this.store(model, { ...profile, rules: prunedRules }, now.toISOString()).profile;\n\t\t}\n\t\treturn profile;\n\t}\n\n\t/** Add or replace one standing rule, enforcing the per-model cap. */\n\taddRule(\n\t\tmodel: string,\n\t\trule: { mode: string; text: string; addedAt?: string; lastFiredAt?: string },\n\t\tnow = new Date(),\n\t): StoredModelAdaptation {\n\t\tconst profile = this.get(model, now);\n\t\tconst at = now.toISOString();\n\t\tconst nextRule: ModelAdaptationRule = {\n\t\t\tmode: rule.mode,\n\t\t\ttext: rule.text,\n\t\t\taddedAt: rule.addedAt ?? at,\n\t\t\tlastFiredAt: rule.lastFiredAt ?? at,\n\t\t};\n\t\treturn this.store(model, { ...profile, rules: mergeRule(profile.rules, nextRule) }, at);\n\t}\n\n\tremoveRule(model: string, mode: string, at = new Date()): boolean {\n\t\tconst profile = this.get(model, at);\n\t\tconst rules = profile.rules.filter((rule) => rule.mode !== mode);\n\t\tif (rules.length === profile.rules.length) return false;\n\t\tthis.store(model, { ...profile, rules }, at.toISOString());\n\t\treturn true;\n\t}\n\n\t/** Update last-fired recency for an existing rule. No-op when absent. */\n\tmarkRuleFired(model: string, mode: string, at = new Date()): StoredModelAdaptation | undefined {\n\t\tconst profile = this.get(model, at);\n\t\tconst rules = profile.rules.map((rule) =>\n\t\t\trule.mode === mode ? { ...rule, lastFiredAt: at.toISOString() } : rule,\n\t\t);\n\t\tif (rules.every((rule, index) => rule === profile.rules[index])) return undefined;\n\t\treturn this.store(model, { ...profile, rules }, at.toISOString());\n\t}\n\n\tsetProtocol(model: string, protocol: ModelProtocolCalibration, at?: string): StoredModelAdaptation {\n\t\tconst now = at ?? (protocol.status === \"failed\" ? protocol.attemptedAt : protocol.calibratedAt);\n\t\tconst profile = this.get(model, new Date(now));\n\t\treturn this.store(model, { ...profile, protocol }, now);\n\t}\n\n\tsetToolProbe(model: string, toolProbe: ModelToolProbe, at?: string): StoredModelAdaptation {\n\t\tconst now = at ?? toolProbe.probedAt;\n\t\tconst profile = this.get(model, new Date(now));\n\t\treturn this.store(model, { ...profile, toolProbe }, now);\n\t}\n\n\tremoveProtocol(model: string, at = new Date()): boolean {\n\t\tconst profile = this.get(model, at);\n\t\tif (!profile.protocol) return false;\n\t\tconst { protocol: _protocol, ...rest } = profile;\n\t\tthis.store(model, rest, at.toISOString());\n\t\treturn true;\n\t}\n\n\tsetTeachStats(model: string, mode: string, stats: ModelTeachStats, at?: string): StoredModelAdaptation {\n\t\tconst now = at ?? new Date().toISOString();\n\t\tconst profile = this.get(model, new Date(now));\n\t\treturn this.store(model, { ...profile, teachStats: { ...profile.teachStats, [mode]: stats } }, now);\n\t}\n\n\t/** Profiles for the current host (default) or an explicit host id. */\n\tgetForHost(hostId?: string): StoredModelAdaptation[] {\n\t\tconst file = this.load();\n\t\treturn Object.values(file.hosts[hostId ?? this.fingerprint().id] ?? {}).map((entry) => ({\n\t\t\t...entry,\n\t\t\tprofile: normalizeProfile(entry.profile),\n\t\t}));\n\t}\n\n\t/** Every stored profile across all hosts (for cross-machine comparisons). */\n\tgetAll(): StoredModelAdaptation[] {\n\t\tconst file = this.load();\n\t\treturn Object.values(file.hosts).flatMap((models) =>\n\t\t\tObject.values(models).map((entry) => ({ ...entry, profile: normalizeProfile(entry.profile) })),\n\t\t);\n\t}\n}\n"]}
1
+ {"version":3,"file":"adaptation-store.js","sourceRoot":"","sources":["../../../src/core/models/adaptation-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAwB,MAAM,oBAAoB,CAAC;AAElF,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAC9B,MAAM,eAAe,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AA6DjD,SAAS,YAAY,GAA2B;IAC/C,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;AAAA,CACrC;AAED,SAAS,gBAAgB,CAAC,OAAoD,EAA0B;IACvG,OAAO;QACN,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,O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\nimport { currentHostFingerprint, type HostFingerprint } from \"./fitness-store.ts\";\n\nconst STORE_VERSION = 1;\nconst MAX_RULES_PER_MODEL = 5;\nconst RETIRE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;\n\nexport interface ModelAdaptationRule {\n\tmode: string;\n\ttext: string;\n\taddedAt: string;\n\tlastFiredAt: string;\n}\n\nexport type ModelProtocolCalibration =\n\t| {\n\t\t\tversion: number;\n\t\t\tstatus?: \"calibrated\";\n\t\t\tvariant: string;\n\t\t\tcalibratedAt: string;\n\t }\n\t| {\n\t\t\tversion: number;\n\t\t\tstatus: \"failed\";\n\t\t\tattemptedAt: string;\n\t\t\tvariantsTried: string[];\n\t };\n\nexport type ModelToolProbeVerdict = \"native\" | \"text-protocol\" | \"none\";\nexport type NativeToolProbeGrade = \"task\" | \"echo-only\" | \"absent\";\n\nexport interface ModelToolProbe {\n\tversion: number;\n\tstatus: ModelToolProbeVerdict;\n\tprobedAt: string;\n\tvariant?: string;\n\tnativeGrade?: NativeToolProbeGrade;\n\tdiagnostic?: string;\n}\n\nexport interface ModelTeachStats {\n\ttaught: number;\n\trecurrenceBefore: number;\n\trecurrenceAfter: number;\n}\n\nexport interface ModelAdaptationProfile {\n\trules: ModelAdaptationRule[];\n\tprotocol?: ModelProtocolCalibration;\n\ttoolProbe?: ModelToolProbe;\n\tteachStats: Record<string, ModelTeachStats>;\n}\n\nexport interface StoredModelAdaptation {\n\tmodel: string;\n\tprofile: ModelAdaptationProfile;\n\tat: string;\n\thost: HostFingerprint;\n}\n\ninterface AdaptationStoreFile {\n\tversion: 1;\n\t/** hostId -> modelRef -> latest stored adaptation profile. */\n\thosts: Record<string, Record<string, StoredModelAdaptation>>;\n}\n\nfunction emptyProfile(): ModelAdaptationProfile {\n\treturn { rules: [], teachStats: {} };\n}\n\nfunction normalizeProfile(profile: Partial<ModelAdaptationProfile> | undefined): ModelAdaptationProfile {\n\treturn {\n\t\trules: Array.isArray(profile?.rules) ? profile.rules.filter(isRule) : [],\n\t\t...(isProtocol(profile?.protocol) && { protocol: profile.protocol }),\n\t\t...(isToolProbe(profile?.toolProbe) && { toolProbe: profile.toolProbe }),\n\t\tteachStats: isRecord(profile?.teachStats) ? filterTeachStats(profile.teachStats) : {},\n\t};\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isRule(value: unknown): value is ModelAdaptationRule {\n\treturn (\n\t\tisRecord(value) &&\n\t\ttypeof value.mode === \"string\" &&\n\t\ttypeof value.text === \"string\" &&\n\t\ttypeof value.addedAt === \"string\" &&\n\t\ttypeof value.lastFiredAt === \"string\"\n\t);\n}\n\nfunction isProtocol(value: unknown): value is ModelProtocolCalibration {\n\tif (!isRecord(value) || typeof value.version !== \"number\") return false;\n\tif (value.status === \"failed\") {\n\t\treturn (\n\t\t\ttypeof value.attemptedAt === \"string\" &&\n\t\t\tArray.isArray(value.variantsTried) &&\n\t\t\tvalue.variantsTried.every((variant) => typeof variant === \"string\")\n\t\t);\n\t}\n\treturn (\n\t\t(value.status === undefined || value.status === \"calibrated\") &&\n\t\ttypeof value.variant === \"string\" &&\n\t\ttypeof value.calibratedAt === \"string\"\n\t);\n}\n\nfunction isToolProbe(value: unknown): value is ModelToolProbe {\n\treturn (\n\t\tisRecord(value) &&\n\t\ttypeof value.version === \"number\" &&\n\t\t(value.status === \"native\" || value.status === \"text-protocol\" || value.status === \"none\") &&\n\t\ttypeof value.probedAt === \"string\" &&\n\t\t(value.variant === undefined || typeof value.variant === \"string\") &&\n\t\t(value.nativeGrade === undefined ||\n\t\t\tvalue.nativeGrade === \"task\" ||\n\t\t\tvalue.nativeGrade === \"echo-only\" ||\n\t\t\tvalue.nativeGrade === \"absent\") &&\n\t\t(value.diagnostic === undefined || typeof value.diagnostic === \"string\")\n\t);\n}\n\nfunction isTeachStats(value: unknown): value is ModelTeachStats {\n\treturn (\n\t\tisRecord(value) &&\n\t\ttypeof value.taught === \"number\" &&\n\t\ttypeof value.recurrenceBefore === \"number\" &&\n\t\ttypeof value.recurrenceAfter === \"number\"\n\t);\n}\n\nfunction filterTeachStats(value: Record<string, unknown>): Record<string, ModelTeachStats> {\n\treturn Object.fromEntries(\n\t\tObject.entries(value).filter((entry): entry is [string, ModelTeachStats] => isTeachStats(entry[1])),\n\t);\n}\n\nfunction ruleRecency(rule: ModelAdaptationRule): number {\n\tconst lastFired = Date.parse(rule.lastFiredAt);\n\tif (Number.isFinite(lastFired)) return lastFired;\n\tconst added = Date.parse(rule.addedAt);\n\treturn Number.isFinite(added) ? added : 0;\n}\n\nfunction pruneRetiredRules(rules: readonly ModelAdaptationRule[], now: Date): ModelAdaptationRule[] {\n\tconst cutoff = now.getTime() - RETIRE_AFTER_MS;\n\treturn rules.filter((rule) => ruleRecency(rule) >= cutoff);\n}\n\nfunction enforceRuleCap(rules: readonly ModelAdaptationRule[]): ModelAdaptationRule[] {\n\tif (rules.length <= MAX_RULES_PER_MODEL) return [...rules];\n\treturn [...rules].sort((a, b) => ruleRecency(b) - ruleRecency(a)).slice(0, MAX_RULES_PER_MODEL);\n}\n\nfunction mergeRule(rules: readonly ModelAdaptationRule[], rule: ModelAdaptationRule): ModelAdaptationRule[] {\n\tconst withoutSameMode = rules.filter((existing) => existing.mode !== rule.mode);\n\treturn enforceRuleCap([...withoutSameMode, rule]);\n}\n\nexport class ModelAdaptationStore {\n\tprivate readonly filePath: string;\n\tprivate readonly fingerprint: () => HostFingerprint;\n\n\tconstructor(filePath: string, options?: { fingerprint?: () => HostFingerprint }) {\n\t\tthis.filePath = filePath;\n\t\tthis.fingerprint = options?.fingerprint ?? currentHostFingerprint;\n\t}\n\n\tstatic forAgentDir(agentDir: string, options?: { fingerprint?: () => HostFingerprint }): ModelAdaptationStore {\n\t\treturn new ModelAdaptationStore(join(agentDir, \"state\", \"model-adaptation.json\"), options);\n\t}\n\n\tprivate load(): AdaptationStoreFile {\n\t\ttry {\n\t\t\tif (!existsSync(this.filePath)) return { version: STORE_VERSION, hosts: {} };\n\t\t\tconst parsed = JSON.parse(readFileSync(this.filePath, \"utf-8\")) as AdaptationStoreFile;\n\t\t\tif (parsed && parsed.version === STORE_VERSION && parsed.hosts && typeof parsed.hosts === \"object\") {\n\t\t\t\treturn parsed;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Unreadable/corrupt store: start fresh in memory; the next save rewrites the file.\n\t\t}\n\t\treturn { version: STORE_VERSION, hosts: {} };\n\t}\n\n\tprivate write(file: AdaptationStoreFile): void {\n\t\tmkdirSync(dirname(this.filePath), { recursive: true });\n\t\twriteFileSync(this.filePath, `${JSON.stringify(file, null, \"\\t\")}\\n`, \"utf-8\");\n\t}\n\n\tprivate store(model: string, profile: ModelAdaptationProfile, at: string): StoredModelAdaptation {\n\t\tconst host = this.fingerprint();\n\t\tconst entry: StoredModelAdaptation = { model, profile: normalizeProfile(profile), at, host };\n\t\tconst file = this.load();\n\t\tfile.hosts[host.id] = { ...(file.hosts[host.id] ?? {}), [model]: entry };\n\t\tthis.write(file);\n\t\treturn entry;\n\t}\n\n\t/** Persist the profile for a model on the CURRENT host. Best-effort, returns the entry. */\n\tsave(model: string, profile: ModelAdaptationProfile, at?: string): StoredModelAdaptation {\n\t\treturn this.store(model, profile, at ?? new Date().toISOString());\n\t}\n\n\t/** Profile for a model on the current host; prunes retired rules before returning. */\n\tget(model: string, now: Date = new Date()): ModelAdaptationProfile {\n\t\tconst host = this.fingerprint();\n\t\tconst file = this.load();\n\t\tconst entry = file.hosts[host.id]?.[model];\n\t\tif (!entry) return emptyProfile();\n\t\tconst profile = normalizeProfile(entry.profile);\n\t\tconst prunedRules = pruneRetiredRules(profile.rules, now);\n\t\tif (prunedRules.length !== profile.rules.length) {\n\t\t\treturn this.store(model, { ...profile, rules: prunedRules }, now.toISOString()).profile;\n\t\t}\n\t\treturn profile;\n\t}\n\n\t/** Add or replace one standing rule, enforcing the per-model cap. */\n\taddRule(\n\t\tmodel: string,\n\t\trule: { mode: string; text: string; addedAt?: string; lastFiredAt?: string },\n\t\tnow = new Date(),\n\t): StoredModelAdaptation {\n\t\tconst profile = this.get(model, now);\n\t\tconst at = now.toISOString();\n\t\tconst nextRule: ModelAdaptationRule = {\n\t\t\tmode: rule.mode,\n\t\t\ttext: rule.text,\n\t\t\taddedAt: rule.addedAt ?? at,\n\t\t\tlastFiredAt: rule.lastFiredAt ?? at,\n\t\t};\n\t\treturn this.store(model, { ...profile, rules: mergeRule(profile.rules, nextRule) }, at);\n\t}\n\n\tremoveRule(model: string, mode: string, at = new Date()): boolean {\n\t\tconst profile = this.get(model, at);\n\t\tconst rules = profile.rules.filter((rule) => rule.mode !== mode);\n\t\tif (rules.length === profile.rules.length) return false;\n\t\tthis.store(model, { ...profile, rules }, at.toISOString());\n\t\treturn true;\n\t}\n\n\t/** Update last-fired recency for an existing rule. No-op when absent. */\n\tmarkRuleFired(model: string, mode: string, at = new Date()): StoredModelAdaptation | undefined {\n\t\tconst profile = this.get(model, at);\n\t\tconst rules = profile.rules.map((rule) =>\n\t\t\trule.mode === mode ? { ...rule, lastFiredAt: at.toISOString() } : rule,\n\t\t);\n\t\tif (rules.every((rule, index) => rule === profile.rules[index])) return undefined;\n\t\treturn this.store(model, { ...profile, rules }, at.toISOString());\n\t}\n\n\tsetProtocol(model: string, protocol: ModelProtocolCalibration, at?: string): StoredModelAdaptation {\n\t\tconst now = at ?? (protocol.status === \"failed\" ? protocol.attemptedAt : protocol.calibratedAt);\n\t\tconst profile = this.get(model, new Date(now));\n\t\treturn this.store(model, { ...profile, protocol }, now);\n\t}\n\n\tsetToolProbe(model: string, toolProbe: ModelToolProbe, at?: string): StoredModelAdaptation {\n\t\tconst now = at ?? toolProbe.probedAt;\n\t\tconst profile = this.get(model, new Date(now));\n\t\treturn this.store(model, { ...profile, toolProbe }, now);\n\t}\n\n\tremoveProtocol(model: string, at = new Date()): boolean {\n\t\tconst profile = this.get(model, at);\n\t\tif (!profile.protocol) return false;\n\t\tconst { protocol: _protocol, ...rest } = profile;\n\t\tthis.store(model, rest, at.toISOString());\n\t\treturn true;\n\t}\n\n\tsetTeachStats(model: string, mode: string, stats: ModelTeachStats, at?: string): StoredModelAdaptation {\n\t\tconst now = at ?? new Date().toISOString();\n\t\tconst profile = this.get(model, new Date(now));\n\t\treturn this.store(model, { ...profile, teachStats: { ...profile.teachStats, [mode]: stats } }, now);\n\t}\n\n\t/** Profiles for the current host (default) or an explicit host id. */\n\tgetForHost(hostId?: string): StoredModelAdaptation[] {\n\t\tconst file = this.load();\n\t\treturn Object.values(file.hosts[hostId ?? this.fingerprint().id] ?? {}).map((entry) => ({\n\t\t\t...entry,\n\t\t\tprofile: normalizeProfile(entry.profile),\n\t\t}));\n\t}\n\n\t/** Every stored profile across all hosts (for cross-machine comparisons). */\n\tgetAll(): StoredModelAdaptation[] {\n\t\tconst file = this.load();\n\t\treturn Object.values(file.hosts).flatMap((models) =>\n\t\t\tObject.values(models).map((entry) => ({ ...entry, profile: normalizeProfile(entry.profile) })),\n\t\t);\n\t}\n}\n"]}
@@ -2,9 +2,9 @@ import type { FitnessRole } from "../../modes/interactive/components/fitness-rol
2
2
  /**
3
3
  * Curated local-model suggestions: a starting roster validated during pi-adaptative's own
4
4
  * small-model research so a user does not have to know WHICH model fits WHICH role. Each entry is
5
- * a pull ref (accepted by /models add) plus the role it was validated for and whether it can call
6
- * tools (Ternary-Bonsai GGUFs ship without a tool-calling template, so they are lane/brain models,
7
- * never executors).
5
+ * an install ref (accepted by /models add) plus the role it was validated for and whether it can use
6
+ * tools. Native tool-calling remains preferred when it works; text-protocol models are listed only
7
+ * when their runtime is pi-managed and the fitness/probe path can calibrate that fallback.
8
8
  *
9
9
  * Honesty: these are SUGGESTIONS, not guarantees. Fitness is a property of the model AND the host
10
10
  * hardware, so no per-model score is baked in here — `/models add` auto-probes on the actual
@@ -19,7 +19,7 @@ export interface ModelSuggestion {
19
19
  pullRef: string;
20
20
  /** Role this model was validated/shaped for. */
21
21
  role: string;
22
- /** True if the model has native tool-calling (required for the executor role). */
22
+ /** True if the model can use tools after host-local probing/calibration (required for executor). */
23
23
  toolCalling: boolean;
24
24
  /** The /fitness assignment target this suggestion maps to, when there is a single-setting slot. */
25
25
  assignRole?: FitnessRole;
@@ -1 +1 @@
1
- {"version":3,"file":"default-model-suggestions.d.ts","sourceRoot":"","sources":["../../../src/core/models/default-model-suggestions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6DAA6D,CAAC;AAE/F;;;;;;;;;;;;GAYG;AAEH,MAAM,WAAW,eAAe;IAC/B,4CAA4C;IAC5C,IAAI,EAAE,MAAM,CAAC;IACb,6DAA6D;IAC7D,OAAO,EAAE,MAAM,CAAC;IAChB,gDAAgD;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,kFAAkF;IAClF,WAAW,EAAE,OAAO,CAAC;IACrB,mGAAmG;IACnG,UAAU,CAAC,EAAE,WAAW,CAAC;IACzB,qFAAqF;IACrF,SAAS,EAAE,MAAM,CAAC;IAClB,oDAAoD;IACpD,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,eAAO,MAAM,yBAAyB,EAAE,SAAS,eAAe,EAoE/D,CAAC;AAEF,gFAAgF;AAChF,wBAAgB,sBAAsB,CAAC,WAAW,GAAE,SAAS,eAAe,EAA8B,GAAG,MAAM,EAAE,CAcpH","sourcesContent":["import type { FitnessRole } from \"../../modes/interactive/components/fitness-role-selector.ts\";\n\n/**\n * Curated local-model suggestions: a starting roster validated during pi-adaptative's own\n * small-model research so a user does not have to know WHICH model fits WHICH role. Each entry is\n * a pull ref (accepted by /models add) plus the role it was validated for and whether it can call\n * tools (Ternary-Bonsai GGUFs ship without a tool-calling template, so they are lane/brain models,\n * never executors).\n *\n * Honesty: these are SUGGESTIONS, not guarantees. Fitness is a property of the model AND the host\n * hardware, so no per-model score is baked in here — `/models add` auto-probes on the actual\n * machine, and the roster only encodes what role each model was SHAPED for. `assignRole` is the\n * /fitness role the suggestion maps to (undefined = no single-setting slot yet; use it as a\n * research/worker lane model).\n */\n\nexport interface ModelSuggestion {\n\t/** Display name in the suggestions list. */\n\tname: string;\n\t/** Ref accepted by /models add and the source normalizer. */\n\tpullRef: string;\n\t/** Role this model was validated/shaped for. */\n\trole: string;\n\t/** True if the model has native tool-calling (required for the executor role). */\n\ttoolCalling: boolean;\n\t/** The /fitness assignment target this suggestion maps to, when there is a single-setting slot. */\n\tassignRole?: FitnessRole;\n\t/** One-line rationale from the validation work; never a fabricated numeric score. */\n\trationale: string;\n\t/** Optional caveat (quant selection, RAM needs). */\n\tnote?: string;\n}\n\nexport const DEFAULT_MODEL_SUGGESTIONS: readonly ModelSuggestion[] = [\n\t{\n\t\tname: \"qwen3:1.7b\",\n\t\tpullRef: \"qwen3:1.7b\",\n\t\trole: \"Toolkit executor / reflex muscle\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"executor\",\n\t\trationale:\n\t\t\t\"Validated as the executor: reliable native tool-calling and low latency, so direct toolkit commands run without retries.\",\n\t},\n\t{\n\t\tname: \"qwen3:0.6b\",\n\t\tpullRef: \"qwen3:0.6b\",\n\t\trole: \"Minimal executor (fastest)\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"executor\",\n\t\trationale:\n\t\t\t\"Fastest local option; on harder requests it can narrate without executing, so prefer it only when speed dominates and requests are simple.\",\n\t},\n\t{\n\t\tname: \"FastContext-1.0-4B\",\n\t\tpullRef: \"hf.co/KikoCis/FastContext-1.0-4B-longctx-imatrix-GGUF:fastcontext4b.Q4_K_M.imx.gguf\",\n\t\trole: \"Repository scout (context_scout)\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"scout\",\n\t\trationale:\n\t\t\t\"The model the context_scout lane is built around (Plan 9): 4B Qwen3, 256K context, trained for read-only repo exploration returning file:line citations. /fitness must pass the tool-calls + research lanes before assignment.\",\n\t\tnote: \"Q4 ≈ 2.5 GB; ~5-6 GB peak with 32-64K KV. Qwen3 template caveat: if tool calls fail the probe, use the Modelfile recipe in docs/scout.md.\",\n\t},\n\t{\n\t\tname: \"Ornith-1.0-9B\",\n\t\tpullRef: \"hf.co/deepreinforce-ai/Ornith-1.0-9B-GGUF:Q4_K_M\",\n\t\trole: \"Agentic-coding worker / router cheap tier\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"router-cheap\",\n\t\trationale:\n\t\t\t\"External candidate (not from pi's own validation research): MIT, Qwen 3.5 base, RL-trained for agentic coding with native tool-calling — the strongest local worker SHAPE in the roster. /fitness on your hardware is the validator.\",\n\t\tnote: \"Q4_K_M ≈ 5.6 GB weights, ~7-8 GB peak with KV — on a 10 GB box run it as the ONLY local model. Qwen 3.5 arch: confirm pi's pinned Ollama supports it and probe tool-calls with /fitness before assigning (template derives from the GGUF). Larger boxes: consider router-medium after a passed worker lane.\",\n\t},\n\t{\n\t\tname: \"Ternary-Bonsai-1.7B\",\n\t\tpullRef: \"hf.co/prism-ml/Ternary-Bonsai-1.7B-gguf\",\n\t\trole: \"Search scout (heavy-lifter)\",\n\t\ttoolCalling: false,\n\t\trationale:\n\t\t\t\"Ternary weights, very fast; strong at structured search plans. No tool-calling template — use it as a research/worker lane model, never an executor.\",\n\t\tnote: \"Pick a GGUF quant the runtime accepts (e.g. :Q8_0). The ternary Q2_0 build needs prism-ml's patched llama.cpp.\",\n\t},\n\t{\n\t\tname: \"Ternary-Bonsai-4B\",\n\t\tpullRef: \"hf.co/prism-ml/Ternary-Bonsai-4B-gguf\",\n\t\trole: \"Context curator / reflex brain / lane analyst\",\n\t\ttoolCalling: false,\n\t\tassignRole: \"curator\",\n\t\trationale:\n\t\t\t\"Validated as the 'brain': strict-JSON interpretation and faithful digests. Drives context curation and the toolkit reflex interpreter. Not a tool-caller.\",\n\t\tnote: \"Pick a GGUF quant the runtime accepts (e.g. :Q8_0).\",\n\t},\n\t{\n\t\tname: \"Ternary-Bonsai-8B\",\n\t\tpullRef: \"hf.co/prism-ml/Ternary-Bonsai-8B-gguf\",\n\t\trole: \"Routing judge (larger machines)\",\n\t\ttoolCalling: false,\n\t\tassignRole: \"judge\",\n\t\trationale:\n\t\t\t\"A judge candidate for machines with more headroom — too slow on ~16GB-class hardware in this research, kept for a bigger box.\",\n\t\tnote: \"Heavy: confirm tok/s with /fitness before committing. Ternary quant may need prism-ml's patched llama.cpp.\",\n\t},\n];\n\n/** Bounded plain-text roster for `/models suggest` and the empty-store hint. */\nexport function formatModelSuggestions(suggestions: readonly ModelSuggestion[] = DEFAULT_MODEL_SUGGESTIONS): string[] {\n\tconst lines = [\n\t\t\"Suggested local models (validated roles from pi's own small-model research; probe on YOUR hardware with /fitness):\",\n\t];\n\tfor (const suggestion of suggestions) {\n\t\tlines.push(\n\t\t\t` - ${suggestion.name} → ${suggestion.role}${suggestion.toolCalling ? \"\" : \" [no tool-calling]\"}`,\n\t\t\t` /models add ${suggestion.pullRef}`,\n\t\t\t` ${suggestion.rationale}`,\n\t\t);\n\t\tif (suggestion.note) lines.push(` note: ${suggestion.note}`);\n\t}\n\tlines.push(\"Add one with /models add <ref> — pi pulls it, probes it, and offers a role in one step.\");\n\treturn lines;\n}\n"]}
1
+ {"version":3,"file":"default-model-suggestions.d.ts","sourceRoot":"","sources":["../../../src/core/models/default-model-suggestions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6DAA6D,CAAC;AAE/F;;;;;;;;;;;;GAYG;AAEH,MAAM,WAAW,eAAe;IAC/B,4CAA4C;IAC5C,IAAI,EAAE,MAAM,CAAC;IACb,6DAA6D;IAC7D,OAAO,EAAE,MAAM,CAAC;IAChB,gDAAgD;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,oGAAoG;IACpG,WAAW,EAAE,OAAO,CAAC;IACrB,mGAAmG;IACnG,UAAU,CAAC,EAAE,WAAW,CAAC;IACzB,qFAAqF;IACrF,SAAS,EAAE,MAAM,CAAC;IAClB,oDAAoD;IACpD,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,eAAO,MAAM,yBAAyB,EAAE,SAAS,eAAe,EA8E/D,CAAC;AAEF,gFAAgF;AAChF,wBAAgB,sBAAsB,CAAC,WAAW,GAAE,SAAS,eAAe,EAA8B,GAAG,MAAM,EAAE,CAcpH","sourcesContent":["import type { FitnessRole } from \"../../modes/interactive/components/fitness-role-selector.ts\";\n\n/**\n * Curated local-model suggestions: a starting roster validated during pi-adaptative's own\n * small-model research so a user does not have to know WHICH model fits WHICH role. Each entry is\n * an install ref (accepted by /models add) plus the role it was validated for and whether it can use\n * tools. Native tool-calling remains preferred when it works; text-protocol models are listed only\n * when their runtime is pi-managed and the fitness/probe path can calibrate that fallback.\n *\n * Honesty: these are SUGGESTIONS, not guarantees. Fitness is a property of the model AND the host\n * hardware, so no per-model score is baked in here — `/models add` auto-probes on the actual\n * machine, and the roster only encodes what role each model was SHAPED for. `assignRole` is the\n * /fitness role the suggestion maps to (undefined = no single-setting slot yet; use it as a\n * research/worker lane model).\n */\n\nexport interface ModelSuggestion {\n\t/** Display name in the suggestions list. */\n\tname: string;\n\t/** Ref accepted by /models add and the source normalizer. */\n\tpullRef: string;\n\t/** Role this model was validated/shaped for. */\n\trole: string;\n\t/** True if the model can use tools after host-local probing/calibration (required for executor). */\n\ttoolCalling: boolean;\n\t/** The /fitness assignment target this suggestion maps to, when there is a single-setting slot. */\n\tassignRole?: FitnessRole;\n\t/** One-line rationale from the validation work; never a fabricated numeric score. */\n\trationale: string;\n\t/** Optional caveat (quant selection, RAM needs). */\n\tnote?: string;\n}\n\nexport const DEFAULT_MODEL_SUGGESTIONS: readonly ModelSuggestion[] = [\n\t{\n\t\tname: \"qwen3:1.7b\",\n\t\tpullRef: \"qwen3:1.7b\",\n\t\trole: \"Toolkit executor / reflex muscle\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"executor\",\n\t\trationale:\n\t\t\t\"Validated as the executor: reliable native tool-calling and low latency, so direct toolkit commands run without retries.\",\n\t},\n\t{\n\t\tname: \"qwen3:0.6b\",\n\t\tpullRef: \"qwen3:0.6b\",\n\t\trole: \"Minimal executor (fastest)\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"executor\",\n\t\trationale:\n\t\t\t\"Fastest local option; on harder requests it can narrate without executing, so prefer it only when speed dominates and requests are simple.\",\n\t},\n\t{\n\t\tname: \"MiniCPM5-1B (full-base)\",\n\t\tpullRef: \"hf.co/openbmb/MiniCPM5-1B\",\n\t\trole: \"Full-base Transformers executor / tiny local muscle\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"executor\",\n\t\trationale:\n\t\t\t\"Full-base Hugging Face MiniCPM5-1B target: pi installs an isolated Transformers runtime and probes native tool-calling first, then calibrates the text protocol only if native tool calls do not work.\",\n\t\tnote: \"Not GGUF/quantized: weights and Python deps land under pi-owned runtime/cache directories, separate from Ollama and system Python.\",\n\t},\n\t{\n\t\tname: \"FastContext-1.0-4B\",\n\t\tpullRef: \"hf.co/KikoCis/FastContext-1.0-4B-longctx-imatrix-GGUF:fastcontext4b.Q4_K_M.imx.gguf\",\n\t\trole: \"Repository scout (context_scout)\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"scout\",\n\t\trationale:\n\t\t\t\"The model the context_scout lane is built around (Plan 9): 4B Qwen3, 256K context, trained for read-only repo exploration returning file:line citations. /fitness must pass the tool-calls + research lanes before assignment.\",\n\t\tnote: \"Q4 ≈ 2.5 GB; ~5-6 GB peak with 32-64K KV. Qwen3 template caveat: if tool calls fail the probe, use the Modelfile recipe in docs/scout.md.\",\n\t},\n\t{\n\t\tname: \"Ornith-1.0-9B\",\n\t\tpullRef: \"hf.co/deepreinforce-ai/Ornith-1.0-9B-GGUF:Q4_K_M\",\n\t\trole: \"Agentic-coding worker / router cheap tier\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"router-cheap\",\n\t\trationale:\n\t\t\t\"External candidate (not from pi's own validation research): MIT, Qwen 3.5 base, RL-trained for agentic coding with native tool-calling — the strongest local worker SHAPE in the roster. /fitness on your hardware is the validator.\",\n\t\tnote: \"Q4_K_M ≈ 5.6 GB weights, ~7-8 GB peak with KV — on a 10 GB box run it as the ONLY local model. Qwen 3.5 arch: confirm pi's pinned Ollama supports it and probe tool-calls with /fitness before assigning (template derives from the GGUF). Larger boxes: consider router-medium after a passed worker lane.\",\n\t},\n\t{\n\t\tname: \"Ternary-Bonsai-1.7B\",\n\t\tpullRef: \"hf.co/prism-ml/Ternary-Bonsai-1.7B-gguf\",\n\t\trole: \"Search scout (heavy-lifter)\",\n\t\ttoolCalling: false,\n\t\trationale:\n\t\t\t\"Ternary weights, very fast; strong at structured search plans. No tool-calling template — use it as a research/worker lane model, never an executor.\",\n\t\tnote: \"Pick a GGUF quant the runtime accepts (e.g. :Q8_0). The ternary Q2_0 build needs prism-ml's patched llama.cpp.\",\n\t},\n\t{\n\t\tname: \"Ternary-Bonsai-4B\",\n\t\tpullRef: \"hf.co/prism-ml/Ternary-Bonsai-4B-gguf\",\n\t\trole: \"Context curator / reflex brain / lane analyst\",\n\t\ttoolCalling: false,\n\t\tassignRole: \"curator\",\n\t\trationale:\n\t\t\t\"Validated as the 'brain': strict-JSON interpretation and faithful digests. Drives context curation and the toolkit reflex interpreter. Not a tool-caller.\",\n\t\tnote: \"Pick a GGUF quant the runtime accepts (e.g. :Q8_0).\",\n\t},\n\t{\n\t\tname: \"Ternary-Bonsai-8B\",\n\t\tpullRef: \"hf.co/prism-ml/Ternary-Bonsai-8B-gguf\",\n\t\trole: \"Routing judge (larger machines)\",\n\t\ttoolCalling: false,\n\t\tassignRole: \"judge\",\n\t\trationale:\n\t\t\t\"A judge candidate for machines with more headroom — too slow on ~16GB-class hardware in this research, kept for a bigger box.\",\n\t\tnote: \"Heavy: confirm tok/s with /fitness before committing. Ternary quant may need prism-ml's patched llama.cpp.\",\n\t},\n];\n\n/** Bounded plain-text roster for `/models suggest` and the empty-store hint. */\nexport function formatModelSuggestions(suggestions: readonly ModelSuggestion[] = DEFAULT_MODEL_SUGGESTIONS): string[] {\n\tconst lines = [\n\t\t\"Suggested local models (validated roles from pi's own small-model research; probe on YOUR hardware with /fitness):\",\n\t];\n\tfor (const suggestion of suggestions) {\n\t\tlines.push(\n\t\t\t` - ${suggestion.name} → ${suggestion.role}${suggestion.toolCalling ? \"\" : \" [no tool-calling]\"}`,\n\t\t\t` /models add ${suggestion.pullRef}`,\n\t\t\t` ${suggestion.rationale}`,\n\t\t);\n\t\tif (suggestion.note) lines.push(` note: ${suggestion.note}`);\n\t}\n\tlines.push(\"Add one with /models add <ref> — pi pulls it, probes it, and offers a role in one step.\");\n\treturn lines;\n}\n"]}
@@ -15,6 +15,15 @@ export const DEFAULT_MODEL_SUGGESTIONS = [
15
15
  assignRole: "executor",
16
16
  rationale: "Fastest local option; on harder requests it can narrate without executing, so prefer it only when speed dominates and requests are simple.",
17
17
  },
18
+ {
19
+ name: "MiniCPM5-1B (full-base)",
20
+ pullRef: "hf.co/openbmb/MiniCPM5-1B",
21
+ role: "Full-base Transformers executor / tiny local muscle",
22
+ toolCalling: true,
23
+ assignRole: "executor",
24
+ rationale: "Full-base Hugging Face MiniCPM5-1B target: pi installs an isolated Transformers runtime and probes native tool-calling first, then calibrates the text protocol only if native tool calls do not work.",
25
+ note: "Not GGUF/quantized: weights and Python deps land under pi-owned runtime/cache directories, separate from Ollama and system Python.",
26
+ },
18
27
  {
19
28
  name: "FastContext-1.0-4B",
20
29
  pullRef: "hf.co/KikoCis/FastContext-1.0-4B-longctx-imatrix-GGUF:fastcontext4b.Q4_K_M.imx.gguf",
@@ -1 +1 @@
1
- {"version":3,"file":"default-model-suggestions.js","sourceRoot":"","sources":["../../../src/core/models/default-model-suggestions.ts"],"names":[],"mappings":"AAiCA,MAAM,CAAC,MAAM,yBAAyB,GAA+B;IACpE;QACC,IAAI,EAAE,YAAY;QAClB,OAAO,EAAE,YAAY;QACrB,IAAI,EAAE,kCAAkC;QACxC,WAAW,EAAE,IAAI;QACjB,UAAU,EAAE,UAAU;QACtB,SAAS,EACR,0HAA0H;KAC3H;IACD;QACC,IAAI,EAAE,YAAY;QAClB,OAA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;QACtC,KAAK,CAAC,IAAI,CACT,OAAO,UAAU,CAAC,IAAI,QAAM,UAAU,CAAC,IAAI,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,oBAAoB,EAAE,EAClG,qBAAqB,UAAU,CAAC,OAAO,EAAE,EACzC,SAAS,UAAU,CAAC,SAAS,EAAE,CAC/B,CAAC;QACF,IAAI,UAAU,CAAC,IAAI;YAAE,KAAK,CAAC,IAAI,CAAC,eAAe,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC;IACnE,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,2FAAyF,CAAC,CAAC;IACtG,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["import type { FitnessRole } from \"../../modes/interactive/components/fitness-role-selector.ts\";\n\n/**\n * Curated local-model suggestions: a starting roster validated during pi-adaptative's own\n * small-model research so a user does not have to know WHICH model fits WHICH role. Each entry is\n * a pull ref (accepted by /models add) plus the role it was validated for and whether it can call\n * tools (Ternary-Bonsai GGUFs ship without a tool-calling template, so they are lane/brain models,\n * never executors).\n *\n * Honesty: these are SUGGESTIONS, not guarantees. Fitness is a property of the model AND the host\n * hardware, so no per-model score is baked in here — `/models add` auto-probes on the actual\n * machine, and the roster only encodes what role each model was SHAPED for. `assignRole` is the\n * /fitness role the suggestion maps to (undefined = no single-setting slot yet; use it as a\n * research/worker lane model).\n */\n\nexport interface ModelSuggestion {\n\t/** Display name in the suggestions list. */\n\tname: string;\n\t/** Ref accepted by /models add and the source normalizer. */\n\tpullRef: string;\n\t/** Role this model was validated/shaped for. */\n\trole: string;\n\t/** True if the model has native tool-calling (required for the executor role). */\n\ttoolCalling: boolean;\n\t/** The /fitness assignment target this suggestion maps to, when there is a single-setting slot. */\n\tassignRole?: FitnessRole;\n\t/** One-line rationale from the validation work; never a fabricated numeric score. */\n\trationale: string;\n\t/** Optional caveat (quant selection, RAM needs). */\n\tnote?: string;\n}\n\nexport const DEFAULT_MODEL_SUGGESTIONS: readonly ModelSuggestion[] = [\n\t{\n\t\tname: \"qwen3:1.7b\",\n\t\tpullRef: \"qwen3:1.7b\",\n\t\trole: \"Toolkit executor / reflex muscle\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"executor\",\n\t\trationale:\n\t\t\t\"Validated as the executor: reliable native tool-calling and low latency, so direct toolkit commands run without retries.\",\n\t},\n\t{\n\t\tname: \"qwen3:0.6b\",\n\t\tpullRef: \"qwen3:0.6b\",\n\t\trole: \"Minimal executor (fastest)\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"executor\",\n\t\trationale:\n\t\t\t\"Fastest local option; on harder requests it can narrate without executing, so prefer it only when speed dominates and requests are simple.\",\n\t},\n\t{\n\t\tname: \"FastContext-1.0-4B\",\n\t\tpullRef: \"hf.co/KikoCis/FastContext-1.0-4B-longctx-imatrix-GGUF:fastcontext4b.Q4_K_M.imx.gguf\",\n\t\trole: \"Repository scout (context_scout)\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"scout\",\n\t\trationale:\n\t\t\t\"The model the context_scout lane is built around (Plan 9): 4B Qwen3, 256K context, trained for read-only repo exploration returning file:line citations. /fitness must pass the tool-calls + research lanes before assignment.\",\n\t\tnote: \"Q4 ≈ 2.5 GB; ~5-6 GB peak with 32-64K KV. Qwen3 template caveat: if tool calls fail the probe, use the Modelfile recipe in docs/scout.md.\",\n\t},\n\t{\n\t\tname: \"Ornith-1.0-9B\",\n\t\tpullRef: \"hf.co/deepreinforce-ai/Ornith-1.0-9B-GGUF:Q4_K_M\",\n\t\trole: \"Agentic-coding worker / router cheap tier\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"router-cheap\",\n\t\trationale:\n\t\t\t\"External candidate (not from pi's own validation research): MIT, Qwen 3.5 base, RL-trained for agentic coding with native tool-calling — the strongest local worker SHAPE in the roster. /fitness on your hardware is the validator.\",\n\t\tnote: \"Q4_K_M ≈ 5.6 GB weights, ~7-8 GB peak with KV — on a 10 GB box run it as the ONLY local model. Qwen 3.5 arch: confirm pi's pinned Ollama supports it and probe tool-calls with /fitness before assigning (template derives from the GGUF). Larger boxes: consider router-medium after a passed worker lane.\",\n\t},\n\t{\n\t\tname: \"Ternary-Bonsai-1.7B\",\n\t\tpullRef: \"hf.co/prism-ml/Ternary-Bonsai-1.7B-gguf\",\n\t\trole: \"Search scout (heavy-lifter)\",\n\t\ttoolCalling: false,\n\t\trationale:\n\t\t\t\"Ternary weights, very fast; strong at structured search plans. No tool-calling template — use it as a research/worker lane model, never an executor.\",\n\t\tnote: \"Pick a GGUF quant the runtime accepts (e.g. :Q8_0). The ternary Q2_0 build needs prism-ml's patched llama.cpp.\",\n\t},\n\t{\n\t\tname: \"Ternary-Bonsai-4B\",\n\t\tpullRef: \"hf.co/prism-ml/Ternary-Bonsai-4B-gguf\",\n\t\trole: \"Context curator / reflex brain / lane analyst\",\n\t\ttoolCalling: false,\n\t\tassignRole: \"curator\",\n\t\trationale:\n\t\t\t\"Validated as the 'brain': strict-JSON interpretation and faithful digests. Drives context curation and the toolkit reflex interpreter. Not a tool-caller.\",\n\t\tnote: \"Pick a GGUF quant the runtime accepts (e.g. :Q8_0).\",\n\t},\n\t{\n\t\tname: \"Ternary-Bonsai-8B\",\n\t\tpullRef: \"hf.co/prism-ml/Ternary-Bonsai-8B-gguf\",\n\t\trole: \"Routing judge (larger machines)\",\n\t\ttoolCalling: false,\n\t\tassignRole: \"judge\",\n\t\trationale:\n\t\t\t\"A judge candidate for machines with more headroom — too slow on ~16GB-class hardware in this research, kept for a bigger box.\",\n\t\tnote: \"Heavy: confirm tok/s with /fitness before committing. Ternary quant may need prism-ml's patched llama.cpp.\",\n\t},\n];\n\n/** Bounded plain-text roster for `/models suggest` and the empty-store hint. */\nexport function formatModelSuggestions(suggestions: readonly ModelSuggestion[] = DEFAULT_MODEL_SUGGESTIONS): string[] {\n\tconst lines = [\n\t\t\"Suggested local models (validated roles from pi's own small-model research; probe on YOUR hardware with /fitness):\",\n\t];\n\tfor (const suggestion of suggestions) {\n\t\tlines.push(\n\t\t\t` - ${suggestion.name} → ${suggestion.role}${suggestion.toolCalling ? \"\" : \" [no tool-calling]\"}`,\n\t\t\t` /models add ${suggestion.pullRef}`,\n\t\t\t` ${suggestion.rationale}`,\n\t\t);\n\t\tif (suggestion.note) lines.push(` note: ${suggestion.note}`);\n\t}\n\tlines.push(\"Add one with /models add <ref> — pi pulls it, probes it, and offers a role in one step.\");\n\treturn lines;\n}\n"]}
1
+ {"version":3,"file":"default-model-suggestions.js","sourceRoot":"","sources":["../../../src/core/models/default-model-suggestions.ts"],"names":[],"mappings":"AAiCA,MAAM,CAAC,MAAM,yBAAyB,GAA+B;IACpE;QACC,IAAI,EAAE,YAAY;QAClB,OAAO,EAAE,YAAY;QACrB,IAAI,EAAE,kCAAkC;QACxC,WAAW,EAAE,IAAI;QACjB,UAAU,EAAE,UAAU;QACtB,SAAS,EACR,0HAA0H;KAC3H;IACD;QACC,IAAI,EAAE,YAAY;QAClB,OAAO,EAAE,YAAY;QACrB,IAAI,EAAE,4BAA4B;QAClC,WAAW,EAAE,IAAI;QACjB,UAAU,EAAE,UAAU;QACtB,SAAS,EACR,4IAA4I;KAC7I;IACD;QACC,IAAI,EAAE,yBAAyB;QAC/B,OAAO,EAAE,2BAA2B;QACpC,IAAI,EAAE,qDAAqD;QAC3D,WAAW,EAAE,IAAI;QACjB,UAAU,EAAE,UAAU;QACtB,SAAS,EACR,wMAAwM;QACzM,IAAI,EAAE,oIAAoI;KAC1I;IACD;QACC,IAAI,EAAE,oBAAoB;QAC1B,OAAO,EAAE,qFAAqF;QAC9F,IAAI,EAAE,kCAAkC;QACxC,WAAW,EAAE,IAAI;QACjB,UAAU,EAAE,OAAO;QACnB,SAAS,EACR,gOAAgO;QACjO,IAAI,EAAE,6IAA2I;KACjJ;IACD;QACC,IAAI,EAAE,eAAe;QACrB,OAAO,EAAE,kDAAkD;QAC3D,IAAI,EAAE,2CAA2C;QACjD,WAAW,EAAE,IAAI;QACjB,UAAU,EA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AAA,CACb","sourcesContent":["import type { FitnessRole } from \"../../modes/interactive/components/fitness-role-selector.ts\";\n\n/**\n * Curated local-model suggestions: a starting roster validated during pi-adaptative's own\n * small-model research so a user does not have to know WHICH model fits WHICH role. Each entry is\n * an install ref (accepted by /models add) plus the role it was validated for and whether it can use\n * tools. Native tool-calling remains preferred when it works; text-protocol models are listed only\n * when their runtime is pi-managed and the fitness/probe path can calibrate that fallback.\n *\n * Honesty: these are SUGGESTIONS, not guarantees. Fitness is a property of the model AND the host\n * hardware, so no per-model score is baked in here — `/models add` auto-probes on the actual\n * machine, and the roster only encodes what role each model was SHAPED for. `assignRole` is the\n * /fitness role the suggestion maps to (undefined = no single-setting slot yet; use it as a\n * research/worker lane model).\n */\n\nexport interface ModelSuggestion {\n\t/** Display name in the suggestions list. */\n\tname: string;\n\t/** Ref accepted by /models add and the source normalizer. */\n\tpullRef: string;\n\t/** Role this model was validated/shaped for. */\n\trole: string;\n\t/** True if the model can use tools after host-local probing/calibration (required for executor). */\n\ttoolCalling: boolean;\n\t/** The /fitness assignment target this suggestion maps to, when there is a single-setting slot. */\n\tassignRole?: FitnessRole;\n\t/** One-line rationale from the validation work; never a fabricated numeric score. */\n\trationale: string;\n\t/** Optional caveat (quant selection, RAM needs). */\n\tnote?: string;\n}\n\nexport const DEFAULT_MODEL_SUGGESTIONS: readonly ModelSuggestion[] = [\n\t{\n\t\tname: \"qwen3:1.7b\",\n\t\tpullRef: \"qwen3:1.7b\",\n\t\trole: \"Toolkit executor / reflex muscle\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"executor\",\n\t\trationale:\n\t\t\t\"Validated as the executor: reliable native tool-calling and low latency, so direct toolkit commands run without retries.\",\n\t},\n\t{\n\t\tname: \"qwen3:0.6b\",\n\t\tpullRef: \"qwen3:0.6b\",\n\t\trole: \"Minimal executor (fastest)\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"executor\",\n\t\trationale:\n\t\t\t\"Fastest local option; on harder requests it can narrate without executing, so prefer it only when speed dominates and requests are simple.\",\n\t},\n\t{\n\t\tname: \"MiniCPM5-1B (full-base)\",\n\t\tpullRef: \"hf.co/openbmb/MiniCPM5-1B\",\n\t\trole: \"Full-base Transformers executor / tiny local muscle\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"executor\",\n\t\trationale:\n\t\t\t\"Full-base Hugging Face MiniCPM5-1B target: pi installs an isolated Transformers runtime and probes native tool-calling first, then calibrates the text protocol only if native tool calls do not work.\",\n\t\tnote: \"Not GGUF/quantized: weights and Python deps land under pi-owned runtime/cache directories, separate from Ollama and system Python.\",\n\t},\n\t{\n\t\tname: \"FastContext-1.0-4B\",\n\t\tpullRef: \"hf.co/KikoCis/FastContext-1.0-4B-longctx-imatrix-GGUF:fastcontext4b.Q4_K_M.imx.gguf\",\n\t\trole: \"Repository scout (context_scout)\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"scout\",\n\t\trationale:\n\t\t\t\"The model the context_scout lane is built around (Plan 9): 4B Qwen3, 256K context, trained for read-only repo exploration returning file:line citations. /fitness must pass the tool-calls + research lanes before assignment.\",\n\t\tnote: \"Q4 ≈ 2.5 GB; ~5-6 GB peak with 32-64K KV. Qwen3 template caveat: if tool calls fail the probe, use the Modelfile recipe in docs/scout.md.\",\n\t},\n\t{\n\t\tname: \"Ornith-1.0-9B\",\n\t\tpullRef: \"hf.co/deepreinforce-ai/Ornith-1.0-9B-GGUF:Q4_K_M\",\n\t\trole: \"Agentic-coding worker / router cheap tier\",\n\t\ttoolCalling: true,\n\t\tassignRole: \"router-cheap\",\n\t\trationale:\n\t\t\t\"External candidate (not from pi's own validation research): MIT, Qwen 3.5 base, RL-trained for agentic coding with native tool-calling — the strongest local worker SHAPE in the roster. /fitness on your hardware is the validator.\",\n\t\tnote: \"Q4_K_M ≈ 5.6 GB weights, ~7-8 GB peak with KV — on a 10 GB box run it as the ONLY local model. Qwen 3.5 arch: confirm pi's pinned Ollama supports it and probe tool-calls with /fitness before assigning (template derives from the GGUF). Larger boxes: consider router-medium after a passed worker lane.\",\n\t},\n\t{\n\t\tname: \"Ternary-Bonsai-1.7B\",\n\t\tpullRef: \"hf.co/prism-ml/Ternary-Bonsai-1.7B-gguf\",\n\t\trole: \"Search scout (heavy-lifter)\",\n\t\ttoolCalling: false,\n\t\trationale:\n\t\t\t\"Ternary weights, very fast; strong at structured search plans. No tool-calling template — use it as a research/worker lane model, never an executor.\",\n\t\tnote: \"Pick a GGUF quant the runtime accepts (e.g. :Q8_0). The ternary Q2_0 build needs prism-ml's patched llama.cpp.\",\n\t},\n\t{\n\t\tname: \"Ternary-Bonsai-4B\",\n\t\tpullRef: \"hf.co/prism-ml/Ternary-Bonsai-4B-gguf\",\n\t\trole: \"Context curator / reflex brain / lane analyst\",\n\t\ttoolCalling: false,\n\t\tassignRole: \"curator\",\n\t\trationale:\n\t\t\t\"Validated as the 'brain': strict-JSON interpretation and faithful digests. Drives context curation and the toolkit reflex interpreter. Not a tool-caller.\",\n\t\tnote: \"Pick a GGUF quant the runtime accepts (e.g. :Q8_0).\",\n\t},\n\t{\n\t\tname: \"Ternary-Bonsai-8B\",\n\t\tpullRef: \"hf.co/prism-ml/Ternary-Bonsai-8B-gguf\",\n\t\trole: \"Routing judge (larger machines)\",\n\t\ttoolCalling: false,\n\t\tassignRole: \"judge\",\n\t\trationale:\n\t\t\t\"A judge candidate for machines with more headroom — too slow on ~16GB-class hardware in this research, kept for a bigger box.\",\n\t\tnote: \"Heavy: confirm tok/s with /fitness before committing. Ternary quant may need prism-ml's patched llama.cpp.\",\n\t},\n];\n\n/** Bounded plain-text roster for `/models suggest` and the empty-store hint. */\nexport function formatModelSuggestions(suggestions: readonly ModelSuggestion[] = DEFAULT_MODEL_SUGGESTIONS): string[] {\n\tconst lines = [\n\t\t\"Suggested local models (validated roles from pi's own small-model research; probe on YOUR hardware with /fitness):\",\n\t];\n\tfor (const suggestion of suggestions) {\n\t\tlines.push(\n\t\t\t` - ${suggestion.name} → ${suggestion.role}${suggestion.toolCalling ? \"\" : \" [no tool-calling]\"}`,\n\t\t\t` /models add ${suggestion.pullRef}`,\n\t\t\t` ${suggestion.rationale}`,\n\t\t);\n\t\tif (suggestion.note) lines.push(` note: ${suggestion.note}`);\n\t}\n\tlines.push(\"Add one with /models add <ref> — pi pulls it, probes it, and offers a role in one step.\");\n\treturn lines;\n}\n"]}
@@ -7,6 +7,8 @@ export interface LocalRegistrationResult {
7
7
  }
8
8
  /** Provider name pi registers pulled local models under (see registerLocalModel below). */
9
9
  export declare const OLLAMA_PROVIDER = "ollama";
10
+ /** Provider name for pi-managed Hugging Face Transformers sidecar models. */
11
+ export declare const HF_TRANSFORMERS_PROVIDER = "pi-hf-transformers";
10
12
  export declare function registerLocalModel(args: {
11
13
  agentDir: string;
12
14
  ref: string;
@@ -14,8 +16,18 @@ export declare function registerLocalModel(args: {
14
16
  contextWindow?: number;
15
17
  servedContextWindow?: number;
16
18
  }): LocalRegistrationResult;
19
+ export declare function registerTransformersModel(args: {
20
+ agentDir: string;
21
+ modelId: string;
22
+ baseUrl: string;
23
+ contextWindow?: number;
24
+ }): LocalRegistrationResult;
17
25
  export declare function unregisterLocalModel(args: {
18
26
  agentDir: string;
19
27
  ref: string;
20
28
  }): LocalRegistrationResult;
29
+ export declare function unregisterTransformersModel(args: {
30
+ agentDir: string;
31
+ modelId: string;
32
+ }): LocalRegistrationResult;
21
33
  //# sourceMappingURL=local-registration.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"local-registration.d.ts","sourceRoot":"","sources":["../../../src/core/models/local-registration.ts"],"names":[],"mappings":"AAwCA,MAAM,WAAW,uBAAuB;IACvC,EAAE,EAAE,OAAO,CAAC;IACZ,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,uFAAuF;IACvF,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,2FAA2F;AAC3F,eAAO,MAAM,eAAe,WAAW,CAAC;AA2BxC,wBAAgB,kBAAkB,CAAC,IAAI,EAAE;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC7B,GAAG,uBAAuB,CAoC1B;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,uBAAuB,CAgBrG","sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Persistent registration for pulled local models: merges an \"ollama\" provider entry into the\n * user's `<agentDir>/models.json` — the exact file ModelRegistry loads at startup — so a pulled\n * model resolves as `ollama/<ref>` immediately AND across sessions (usable as session model,\n * lane model, judge, or curator).\n *\n * Non-destructive contract: the file is parsed with STRICT JSON first; a file that only parses\n * with comments/relaxed syntax is the user's hand-authored config and is never rewritten — the\n * caller gets `manualSnippet` to show instead.\n */\n\ninterface ModelsJsonModel {\n\tid: string;\n\tname?: string;\n\tcontextWindow?: number;\n\t/** Measured by the local capacity probe; compaction uses min(contextWindow, servedContextWindow). */\n\tservedContextWindow?: number;\n\tmaxTokens?: number;\n\treasoning?: boolean;\n\tinput?: string[];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n}\n\ninterface ModelsJson {\n\tproviders: Record<\n\t\tstring,\n\t\t{\n\t\t\tbaseUrl?: string;\n\t\t\tapi?: string;\n\t\t\tapiKey?: string;\n\t\t\tmodels?: ModelsJsonModel[];\n\t\t\t[key: string]: unknown;\n\t\t}\n\t>;\n\t[key: string]: unknown;\n}\n\nexport interface LocalRegistrationResult {\n\tok: boolean;\n\tmodelsJsonPath: string;\n\treason?: string;\n\t/** When the file cannot be safely rewritten: the entry the user should add by hand. */\n\tmanualSnippet?: string;\n}\n\n/** Provider name pi registers pulled local models under (see registerLocalModel below). */\nexport const OLLAMA_PROVIDER = \"ollama\";\n\nfunction localModelEntry(ref: string, contextWindow: number, servedContextWindow?: number): ModelsJsonModel {\n\treturn {\n\t\tid: ref,\n\t\tname: ref,\n\t\tcontextWindow,\n\t\t...(servedContextWindow !== undefined ? { servedContextWindow } : {}),\n\t\tmaxTokens: 2048,\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t};\n}\n\nfunction loadStrict(path: string): { json?: ModelsJson; reason?: string } {\n\tif (!existsSync(path)) return { json: { providers: {} } };\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as ModelsJson;\n\t\tif (!parsed || typeof parsed !== \"object\") return { reason: \"models.json is not a JSON object\" };\n\t\tparsed.providers = parsed.providers ?? {};\n\t\treturn { json: parsed };\n\t} catch {\n\t\treturn { reason: \"models.json uses comments/relaxed JSON — pi will not rewrite a hand-authored file\" };\n\t}\n}\n\nexport function registerLocalModel(args: {\n\tagentDir: string;\n\tref: string;\n\tbaseUrl: string;\n\tcontextWindow?: number;\n\tservedContextWindow?: number;\n}): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst contextWindow = args.contextWindow ?? 8192;\n\tconst entry = localModelEntry(args.ref, contextWindow, args.servedContextWindow);\n\tconst providerBase = {\n\t\tbaseUrl: `${args.baseUrl.replace(/\\/$/, \"\")}/v1`,\n\t\tapi: \"openai-completions\",\n\t\tapiKey: \"ollama\",\n\t};\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmodelsJsonPath,\n\t\t\treason,\n\t\t\tmanualSnippet: JSON.stringify(\n\t\t\t\t{ providers: { [OLLAMA_PROVIDER]: { ...providerBase, models: [entry] } } },\n\t\t\t\tnull,\n\t\t\t\t\"\\t\",\n\t\t\t),\n\t\t};\n\t}\n\tjson.providers[OLLAMA_PROVIDER] ??= { ...providerBase, models: [] };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tprovider.baseUrl ??= providerBase.baseUrl;\n\tprovider.api ??= providerBase.api;\n\tprovider.apiKey ??= providerBase.apiKey;\n\tprovider.models ??= [];\n\tconst existing = provider.models.findIndex((model) => model.id === args.ref);\n\tif (existing >= 0) {\n\t\tprovider.models[existing] = { ...provider.models[existing], ...entry };\n\t} else {\n\t\tprovider.models.push(entry);\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n\nexport function unregisterLocalModel(args: { agentDir: string; ref: string }): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) return { ok: false, modelsJsonPath, reason };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tif (!provider?.models) return { ok: true, modelsJsonPath };\n\tconst before = provider.models.length;\n\tprovider.models = provider.models.filter((model) => model.id !== args.ref);\n\tif (provider.models.length === before) return { ok: true, modelsJsonPath };\n\t// Drop the whole provider entry when its last pi-registered model goes (leave user fields alone\n\t// if they added any models themselves — only an all-pi-managed empty list is removed).\n\tif (provider.models.length === 0) {\n\t\tdelete json.providers[OLLAMA_PROVIDER];\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n"]}
1
+ {"version":3,"file":"local-registration.d.ts","sourceRoot":"","sources":["../../../src/core/models/local-registration.ts"],"names":[],"mappings":"AA4CA,MAAM,WAAW,uBAAuB;IACvC,EAAE,EAAE,OAAO,CAAC;IACZ,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,uFAAuF;IACvF,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,2FAA2F;AAC3F,eAAO,MAAM,eAAe,WAAW,CAAC;AACxC,6EAA6E;AAC7E,eAAO,MAAM,wBAAwB,uBAAuB,CAAC;AAyC7D,wBAAgB,kBAAkB,CAAC,IAAI,EAAE;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC7B,GAAG,uBAAuB,CAoC1B;AAED,wBAAgB,yBAAyB,CAAC,IAAI,EAAE;IAC/C,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB,GAAG,uBAAuB,CAqC1B;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,uBAAuB,CAgBrG;AAED,wBAAgB,2BAA2B,CAAC,IAAI,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,uBAAuB,CAchH","sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Persistent registration for pulled local models: merges an \"ollama\" provider entry into the\n * user's `<agentDir>/models.json` — the exact file ModelRegistry loads at startup — so a pulled\n * model resolves as `ollama/<ref>` immediately AND across sessions (usable as session model,\n * lane model, judge, or curator).\n *\n * Non-destructive contract: the file is parsed with STRICT JSON first; a file that only parses\n * with comments/relaxed syntax is the user's hand-authored config and is never rewritten — the\n * caller gets `manualSnippet` to show instead.\n */\n\ninterface ModelsJsonModel {\n\tid: string;\n\tname?: string;\n\tapi?: string;\n\tbaseUrl?: string;\n\tcontextWindow?: number;\n\t/** Measured by the local capacity probe; compaction uses min(contextWindow, servedContextWindow). */\n\tservedContextWindow?: number;\n\tmaxTokens?: number;\n\treasoning?: boolean;\n\ttextToolCallProtocol?: boolean;\n\tinput?: string[];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\tcompat?: Record<string, unknown>;\n}\n\ninterface ModelsJson {\n\tproviders: Record<\n\t\tstring,\n\t\t{\n\t\t\tbaseUrl?: string;\n\t\t\tapi?: string;\n\t\t\tapiKey?: string;\n\t\t\tmodels?: ModelsJsonModel[];\n\t\t\t[key: string]: unknown;\n\t\t}\n\t>;\n\t[key: string]: unknown;\n}\n\nexport interface LocalRegistrationResult {\n\tok: boolean;\n\tmodelsJsonPath: string;\n\treason?: string;\n\t/** When the file cannot be safely rewritten: the entry the user should add by hand. */\n\tmanualSnippet?: string;\n}\n\n/** Provider name pi registers pulled local models under (see registerLocalModel below). */\nexport const OLLAMA_PROVIDER = \"ollama\";\n/** Provider name for pi-managed Hugging Face Transformers sidecar models. */\nexport const HF_TRANSFORMERS_PROVIDER = \"pi-hf-transformers\";\n\nfunction localModelEntry(ref: string, contextWindow: number, servedContextWindow?: number): ModelsJsonModel {\n\treturn {\n\t\tid: ref,\n\t\tname: ref,\n\t\tcontextWindow,\n\t\t...(servedContextWindow !== undefined ? { servedContextWindow } : {}),\n\t\tmaxTokens: 2048,\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t};\n}\n\nfunction transformersModelEntry(args: { modelId: string; baseUrl: string; contextWindow?: number }): ModelsJsonModel {\n\treturn {\n\t\tid: args.modelId,\n\t\tname: args.modelId,\n\t\tbaseUrl: `${args.baseUrl.replace(/\\/$/, \"\")}/v1`,\n\t\tcontextWindow: args.contextWindow ?? 131_072,\n\t\tmaxTokens: 1024,\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcompat: { supportsUsageInStreaming: false },\n\t};\n}\n\nfunction loadStrict(path: string): { json?: ModelsJson; reason?: string } {\n\tif (!existsSync(path)) return { json: { providers: {} } };\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as ModelsJson;\n\t\tif (!parsed || typeof parsed !== \"object\") return { reason: \"models.json is not a JSON object\" };\n\t\tparsed.providers = parsed.providers ?? {};\n\t\treturn { json: parsed };\n\t} catch {\n\t\treturn { reason: \"models.json uses comments/relaxed JSON — pi will not rewrite a hand-authored file\" };\n\t}\n}\n\nexport function registerLocalModel(args: {\n\tagentDir: string;\n\tref: string;\n\tbaseUrl: string;\n\tcontextWindow?: number;\n\tservedContextWindow?: number;\n}): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst contextWindow = args.contextWindow ?? 8192;\n\tconst entry = localModelEntry(args.ref, contextWindow, args.servedContextWindow);\n\tconst providerBase = {\n\t\tbaseUrl: `${args.baseUrl.replace(/\\/$/, \"\")}/v1`,\n\t\tapi: \"openai-completions\",\n\t\tapiKey: \"ollama\",\n\t};\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmodelsJsonPath,\n\t\t\treason,\n\t\t\tmanualSnippet: JSON.stringify(\n\t\t\t\t{ providers: { [OLLAMA_PROVIDER]: { ...providerBase, models: [entry] } } },\n\t\t\t\tnull,\n\t\t\t\t\"\\t\",\n\t\t\t),\n\t\t};\n\t}\n\tjson.providers[OLLAMA_PROVIDER] ??= { ...providerBase, models: [] };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tprovider.baseUrl ??= providerBase.baseUrl;\n\tprovider.api ??= providerBase.api;\n\tprovider.apiKey ??= providerBase.apiKey;\n\tprovider.models ??= [];\n\tconst existing = provider.models.findIndex((model) => model.id === args.ref);\n\tif (existing >= 0) {\n\t\tprovider.models[existing] = { ...provider.models[existing], ...entry };\n\t} else {\n\t\tprovider.models.push(entry);\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n\nexport function registerTransformersModel(args: {\n\tagentDir: string;\n\tmodelId: string;\n\tbaseUrl: string;\n\tcontextWindow?: number;\n}): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst entry = transformersModelEntry(args);\n\tconst providerBase = {\n\t\tname: \"Hugging Face Transformers (pi-managed)\",\n\t\tbaseUrl: entry.baseUrl,\n\t\tapi: \"openai-completions\",\n\t\tapiKey: \"pi-transformers\",\n\t};\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmodelsJsonPath,\n\t\t\treason,\n\t\t\tmanualSnippet: JSON.stringify(\n\t\t\t\t{ providers: { [HF_TRANSFORMERS_PROVIDER]: { ...providerBase, models: [entry] } } },\n\t\t\t\tnull,\n\t\t\t\t\"\\t\",\n\t\t\t),\n\t\t};\n\t}\n\tjson.providers[HF_TRANSFORMERS_PROVIDER] ??= { ...providerBase, models: [] };\n\tconst provider = json.providers[HF_TRANSFORMERS_PROVIDER];\n\tprovider.name ??= providerBase.name;\n\tprovider.baseUrl ??= providerBase.baseUrl;\n\tprovider.api ??= providerBase.api;\n\tprovider.apiKey ??= providerBase.apiKey;\n\tprovider.models ??= [];\n\tconst existing = provider.models.findIndex((model) => model.id === args.modelId);\n\tif (existing >= 0) {\n\t\tprovider.models[existing] = { ...provider.models[existing], ...entry };\n\t} else {\n\t\tprovider.models.push(entry);\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n\nexport function unregisterLocalModel(args: { agentDir: string; ref: string }): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) return { ok: false, modelsJsonPath, reason };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tif (!provider?.models) return { ok: true, modelsJsonPath };\n\tconst before = provider.models.length;\n\tprovider.models = provider.models.filter((model) => model.id !== args.ref);\n\tif (provider.models.length === before) return { ok: true, modelsJsonPath };\n\t// Drop the whole provider entry when its last pi-registered model goes (leave user fields alone\n\t// if they added any models themselves — only an all-pi-managed empty list is removed).\n\tif (provider.models.length === 0) {\n\t\tdelete json.providers[OLLAMA_PROVIDER];\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n\nexport function unregisterTransformersModel(args: { agentDir: string; modelId: string }): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) return { ok: false, modelsJsonPath, reason };\n\tconst provider = json.providers[HF_TRANSFORMERS_PROVIDER];\n\tif (!provider?.models) return { ok: true, modelsJsonPath };\n\tconst before = provider.models.length;\n\tprovider.models = provider.models.filter((model) => model.id !== args.modelId);\n\tif (provider.models.length === before) return { ok: true, modelsJsonPath };\n\tif (provider.models.length === 0) {\n\t\tdelete json.providers[HF_TRANSFORMERS_PROVIDER];\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n"]}
@@ -2,6 +2,8 @@ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  /** Provider name pi registers pulled local models under (see registerLocalModel below). */
4
4
  export const OLLAMA_PROVIDER = "ollama";
5
+ /** Provider name for pi-managed Hugging Face Transformers sidecar models. */
6
+ export const HF_TRANSFORMERS_PROVIDER = "pi-hf-transformers";
5
7
  function localModelEntry(ref, contextWindow, servedContextWindow) {
6
8
  return {
7
9
  id: ref,
@@ -14,6 +16,19 @@ function localModelEntry(ref, contextWindow, servedContextWindow) {
14
16
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
15
17
  };
16
18
  }
19
+ function transformersModelEntry(args) {
20
+ return {
21
+ id: args.modelId,
22
+ name: args.modelId,
23
+ baseUrl: `${args.baseUrl.replace(/\/$/, "")}/v1`,
24
+ contextWindow: args.contextWindow ?? 131_072,
25
+ maxTokens: 1024,
26
+ reasoning: false,
27
+ input: ["text"],
28
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
29
+ compat: { supportsUsageInStreaming: false },
30
+ };
31
+ }
17
32
  function loadStrict(path) {
18
33
  if (!existsSync(path))
19
34
  return { json: { providers: {} } };
@@ -62,6 +77,41 @@ export function registerLocalModel(args) {
62
77
  writeFileSync(modelsJsonPath, `${JSON.stringify(json, null, "\t")}\n`, "utf-8");
63
78
  return { ok: true, modelsJsonPath };
64
79
  }
80
+ export function registerTransformersModel(args) {
81
+ const modelsJsonPath = join(args.agentDir, "models.json");
82
+ const entry = transformersModelEntry(args);
83
+ const providerBase = {
84
+ name: "Hugging Face Transformers (pi-managed)",
85
+ baseUrl: entry.baseUrl,
86
+ api: "openai-completions",
87
+ apiKey: "pi-transformers",
88
+ };
89
+ const { json, reason } = loadStrict(modelsJsonPath);
90
+ if (!json) {
91
+ return {
92
+ ok: false,
93
+ modelsJsonPath,
94
+ reason,
95
+ manualSnippet: JSON.stringify({ providers: { [HF_TRANSFORMERS_PROVIDER]: { ...providerBase, models: [entry] } } }, null, "\t"),
96
+ };
97
+ }
98
+ json.providers[HF_TRANSFORMERS_PROVIDER] ??= { ...providerBase, models: [] };
99
+ const provider = json.providers[HF_TRANSFORMERS_PROVIDER];
100
+ provider.name ??= providerBase.name;
101
+ provider.baseUrl ??= providerBase.baseUrl;
102
+ provider.api ??= providerBase.api;
103
+ provider.apiKey ??= providerBase.apiKey;
104
+ provider.models ??= [];
105
+ const existing = provider.models.findIndex((model) => model.id === args.modelId);
106
+ if (existing >= 0) {
107
+ provider.models[existing] = { ...provider.models[existing], ...entry };
108
+ }
109
+ else {
110
+ provider.models.push(entry);
111
+ }
112
+ writeFileSync(modelsJsonPath, `${JSON.stringify(json, null, "\t")}\n`, "utf-8");
113
+ return { ok: true, modelsJsonPath };
114
+ }
65
115
  export function unregisterLocalModel(args) {
66
116
  const modelsJsonPath = join(args.agentDir, "models.json");
67
117
  const { json, reason } = loadStrict(modelsJsonPath);
@@ -82,4 +132,22 @@ export function unregisterLocalModel(args) {
82
132
  writeFileSync(modelsJsonPath, `${JSON.stringify(json, null, "\t")}\n`, "utf-8");
83
133
  return { ok: true, modelsJsonPath };
84
134
  }
135
+ export function unregisterTransformersModel(args) {
136
+ const modelsJsonPath = join(args.agentDir, "models.json");
137
+ const { json, reason } = loadStrict(modelsJsonPath);
138
+ if (!json)
139
+ return { ok: false, modelsJsonPath, reason };
140
+ const provider = json.providers[HF_TRANSFORMERS_PROVIDER];
141
+ if (!provider?.models)
142
+ return { ok: true, modelsJsonPath };
143
+ const before = provider.models.length;
144
+ provider.models = provider.models.filter((model) => model.id !== args.modelId);
145
+ if (provider.models.length === before)
146
+ return { ok: true, modelsJsonPath };
147
+ if (provider.models.length === 0) {
148
+ delete json.providers[HF_TRANSFORMERS_PROVIDER];
149
+ }
150
+ writeFileSync(modelsJsonPath, `${JSON.stringify(json, null, "\t")}\n`, "utf-8");
151
+ return { ok: true, modelsJsonPath };
152
+ }
85
153
  //# sourceMappingURL=local-registration.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"local-registration.js","sourceRoot":"","sources":["../../../src/core/models/local-registration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AA+CjC,2FAA2F;AAC3F,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAC;AAExC,SAAS,eAAe,CAAC,GAAW,EAAE,aAAqB,EAAE,mBAA4B,EAAmB;IAC3G,OAAO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AAM,KAAK,CAAC,EAAE,CAAC;QAClC,OAAO,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACxC,CAAC;IACD,aAAa,CAAC,cAAc,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAChF,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAAA,CACpC","sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Persistent registration for pulled local models: merges an \"ollama\" provider entry into the\n * user's `<agentDir>/models.json` — the exact file ModelRegistry loads at startup — so a pulled\n * model resolves as `ollama/<ref>` immediately AND across sessions (usable as session model,\n * lane model, judge, or curator).\n *\n * Non-destructive contract: the file is parsed with STRICT JSON first; a file that only parses\n * with comments/relaxed syntax is the user's hand-authored config and is never rewritten — the\n * caller gets `manualSnippet` to show instead.\n */\n\ninterface ModelsJsonModel {\n\tid: string;\n\tname?: string;\n\tcontextWindow?: number;\n\t/** Measured by the local capacity probe; compaction uses min(contextWindow, servedContextWindow). */\n\tservedContextWindow?: number;\n\tmaxTokens?: number;\n\treasoning?: boolean;\n\tinput?: string[];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n}\n\ninterface ModelsJson {\n\tproviders: Record<\n\t\tstring,\n\t\t{\n\t\t\tbaseUrl?: string;\n\t\t\tapi?: string;\n\t\t\tapiKey?: string;\n\t\t\tmodels?: ModelsJsonModel[];\n\t\t\t[key: string]: unknown;\n\t\t}\n\t>;\n\t[key: string]: unknown;\n}\n\nexport interface LocalRegistrationResult {\n\tok: boolean;\n\tmodelsJsonPath: string;\n\treason?: string;\n\t/** When the file cannot be safely rewritten: the entry the user should add by hand. */\n\tmanualSnippet?: string;\n}\n\n/** Provider name pi registers pulled local models under (see registerLocalModel below). */\nexport const OLLAMA_PROVIDER = \"ollama\";\n\nfunction localModelEntry(ref: string, contextWindow: number, servedContextWindow?: number): ModelsJsonModel {\n\treturn {\n\t\tid: ref,\n\t\tname: ref,\n\t\tcontextWindow,\n\t\t...(servedContextWindow !== undefined ? { servedContextWindow } : {}),\n\t\tmaxTokens: 2048,\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t};\n}\n\nfunction loadStrict(path: string): { json?: ModelsJson; reason?: string } {\n\tif (!existsSync(path)) return { json: { providers: {} } };\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as ModelsJson;\n\t\tif (!parsed || typeof parsed !== \"object\") return { reason: \"models.json is not a JSON object\" };\n\t\tparsed.providers = parsed.providers ?? {};\n\t\treturn { json: parsed };\n\t} catch {\n\t\treturn { reason: \"models.json uses comments/relaxed JSON — pi will not rewrite a hand-authored file\" };\n\t}\n}\n\nexport function registerLocalModel(args: {\n\tagentDir: string;\n\tref: string;\n\tbaseUrl: string;\n\tcontextWindow?: number;\n\tservedContextWindow?: number;\n}): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst contextWindow = args.contextWindow ?? 8192;\n\tconst entry = localModelEntry(args.ref, contextWindow, args.servedContextWindow);\n\tconst providerBase = {\n\t\tbaseUrl: `${args.baseUrl.replace(/\\/$/, \"\")}/v1`,\n\t\tapi: \"openai-completions\",\n\t\tapiKey: \"ollama\",\n\t};\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmodelsJsonPath,\n\t\t\treason,\n\t\t\tmanualSnippet: JSON.stringify(\n\t\t\t\t{ providers: { [OLLAMA_PROVIDER]: { ...providerBase, models: [entry] } } },\n\t\t\t\tnull,\n\t\t\t\t\"\\t\",\n\t\t\t),\n\t\t};\n\t}\n\tjson.providers[OLLAMA_PROVIDER] ??= { ...providerBase, models: [] };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tprovider.baseUrl ??= providerBase.baseUrl;\n\tprovider.api ??= providerBase.api;\n\tprovider.apiKey ??= providerBase.apiKey;\n\tprovider.models ??= [];\n\tconst existing = provider.models.findIndex((model) => model.id === args.ref);\n\tif (existing >= 0) {\n\t\tprovider.models[existing] = { ...provider.models[existing], ...entry };\n\t} else {\n\t\tprovider.models.push(entry);\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n\nexport function unregisterLocalModel(args: { agentDir: string; ref: string }): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) return { ok: false, modelsJsonPath, reason };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tif (!provider?.models) return { ok: true, modelsJsonPath };\n\tconst before = provider.models.length;\n\tprovider.models = provider.models.filter((model) => model.id !== args.ref);\n\tif (provider.models.length === before) return { ok: true, modelsJsonPath };\n\t// Drop the whole provider entry when its last pi-registered model goes (leave user fields alone\n\t// if they added any models themselves — only an all-pi-managed empty list is removed).\n\tif (provider.models.length === 0) {\n\t\tdelete json.providers[OLLAMA_PROVIDER];\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n"]}
1
+ {"version":3,"file":"local-registration.js","sourceRoot":"","sources":["../../../src/core/models/local-registration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAmDjC,2FAA2F;AAC3F,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAC;AACxC,6EAA6E;AAC7E,MAAM,CAAC,MAAM,wBAAwB,GAAG,oBAAoB,CAAC;AAE7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IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAChF,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAAA,CACpC","sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Persistent registration for pulled local models: merges an \"ollama\" provider entry into the\n * user's `<agentDir>/models.json` — the exact file ModelRegistry loads at startup — so a pulled\n * model resolves as `ollama/<ref>` immediately AND across sessions (usable as session model,\n * lane model, judge, or curator).\n *\n * Non-destructive contract: the file is parsed with STRICT JSON first; a file that only parses\n * with comments/relaxed syntax is the user's hand-authored config and is never rewritten — the\n * caller gets `manualSnippet` to show instead.\n */\n\ninterface ModelsJsonModel {\n\tid: string;\n\tname?: string;\n\tapi?: string;\n\tbaseUrl?: string;\n\tcontextWindow?: number;\n\t/** Measured by the local capacity probe; compaction uses min(contextWindow, servedContextWindow). */\n\tservedContextWindow?: number;\n\tmaxTokens?: number;\n\treasoning?: boolean;\n\ttextToolCallProtocol?: boolean;\n\tinput?: string[];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\tcompat?: Record<string, unknown>;\n}\n\ninterface ModelsJson {\n\tproviders: Record<\n\t\tstring,\n\t\t{\n\t\t\tbaseUrl?: string;\n\t\t\tapi?: string;\n\t\t\tapiKey?: string;\n\t\t\tmodels?: ModelsJsonModel[];\n\t\t\t[key: string]: unknown;\n\t\t}\n\t>;\n\t[key: string]: unknown;\n}\n\nexport interface LocalRegistrationResult {\n\tok: boolean;\n\tmodelsJsonPath: string;\n\treason?: string;\n\t/** When the file cannot be safely rewritten: the entry the user should add by hand. */\n\tmanualSnippet?: string;\n}\n\n/** Provider name pi registers pulled local models under (see registerLocalModel below). */\nexport const OLLAMA_PROVIDER = \"ollama\";\n/** Provider name for pi-managed Hugging Face Transformers sidecar models. */\nexport const HF_TRANSFORMERS_PROVIDER = \"pi-hf-transformers\";\n\nfunction localModelEntry(ref: string, contextWindow: number, servedContextWindow?: number): ModelsJsonModel {\n\treturn {\n\t\tid: ref,\n\t\tname: ref,\n\t\tcontextWindow,\n\t\t...(servedContextWindow !== undefined ? { servedContextWindow } : {}),\n\t\tmaxTokens: 2048,\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t};\n}\n\nfunction transformersModelEntry(args: { modelId: string; baseUrl: string; contextWindow?: number }): ModelsJsonModel {\n\treturn {\n\t\tid: args.modelId,\n\t\tname: args.modelId,\n\t\tbaseUrl: `${args.baseUrl.replace(/\\/$/, \"\")}/v1`,\n\t\tcontextWindow: args.contextWindow ?? 131_072,\n\t\tmaxTokens: 1024,\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcompat: { supportsUsageInStreaming: false },\n\t};\n}\n\nfunction loadStrict(path: string): { json?: ModelsJson; reason?: string } {\n\tif (!existsSync(path)) return { json: { providers: {} } };\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as ModelsJson;\n\t\tif (!parsed || typeof parsed !== \"object\") return { reason: \"models.json is not a JSON object\" };\n\t\tparsed.providers = parsed.providers ?? {};\n\t\treturn { json: parsed };\n\t} catch {\n\t\treturn { reason: \"models.json uses comments/relaxed JSON — pi will not rewrite a hand-authored file\" };\n\t}\n}\n\nexport function registerLocalModel(args: {\n\tagentDir: string;\n\tref: string;\n\tbaseUrl: string;\n\tcontextWindow?: number;\n\tservedContextWindow?: number;\n}): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst contextWindow = args.contextWindow ?? 8192;\n\tconst entry = localModelEntry(args.ref, contextWindow, args.servedContextWindow);\n\tconst providerBase = {\n\t\tbaseUrl: `${args.baseUrl.replace(/\\/$/, \"\")}/v1`,\n\t\tapi: \"openai-completions\",\n\t\tapiKey: \"ollama\",\n\t};\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmodelsJsonPath,\n\t\t\treason,\n\t\t\tmanualSnippet: JSON.stringify(\n\t\t\t\t{ providers: { [OLLAMA_PROVIDER]: { ...providerBase, models: [entry] } } },\n\t\t\t\tnull,\n\t\t\t\t\"\\t\",\n\t\t\t),\n\t\t};\n\t}\n\tjson.providers[OLLAMA_PROVIDER] ??= { ...providerBase, models: [] };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tprovider.baseUrl ??= providerBase.baseUrl;\n\tprovider.api ??= providerBase.api;\n\tprovider.apiKey ??= providerBase.apiKey;\n\tprovider.models ??= [];\n\tconst existing = provider.models.findIndex((model) => model.id === args.ref);\n\tif (existing >= 0) {\n\t\tprovider.models[existing] = { ...provider.models[existing], ...entry };\n\t} else {\n\t\tprovider.models.push(entry);\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n\nexport function registerTransformersModel(args: {\n\tagentDir: string;\n\tmodelId: string;\n\tbaseUrl: string;\n\tcontextWindow?: number;\n}): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst entry = transformersModelEntry(args);\n\tconst providerBase = {\n\t\tname: \"Hugging Face Transformers (pi-managed)\",\n\t\tbaseUrl: entry.baseUrl,\n\t\tapi: \"openai-completions\",\n\t\tapiKey: \"pi-transformers\",\n\t};\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmodelsJsonPath,\n\t\t\treason,\n\t\t\tmanualSnippet: JSON.stringify(\n\t\t\t\t{ providers: { [HF_TRANSFORMERS_PROVIDER]: { ...providerBase, models: [entry] } } },\n\t\t\t\tnull,\n\t\t\t\t\"\\t\",\n\t\t\t),\n\t\t};\n\t}\n\tjson.providers[HF_TRANSFORMERS_PROVIDER] ??= { ...providerBase, models: [] };\n\tconst provider = json.providers[HF_TRANSFORMERS_PROVIDER];\n\tprovider.name ??= providerBase.name;\n\tprovider.baseUrl ??= providerBase.baseUrl;\n\tprovider.api ??= providerBase.api;\n\tprovider.apiKey ??= providerBase.apiKey;\n\tprovider.models ??= [];\n\tconst existing = provider.models.findIndex((model) => model.id === args.modelId);\n\tif (existing >= 0) {\n\t\tprovider.models[existing] = { ...provider.models[existing], ...entry };\n\t} else {\n\t\tprovider.models.push(entry);\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n\nexport function unregisterLocalModel(args: { agentDir: string; ref: string }): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) return { ok: false, modelsJsonPath, reason };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tif (!provider?.models) return { ok: true, modelsJsonPath };\n\tconst before = provider.models.length;\n\tprovider.models = provider.models.filter((model) => model.id !== args.ref);\n\tif (provider.models.length === before) return { ok: true, modelsJsonPath };\n\t// Drop the whole provider entry when its last pi-registered model goes (leave user fields alone\n\t// if they added any models themselves — only an all-pi-managed empty list is removed).\n\tif (provider.models.length === 0) {\n\t\tdelete json.providers[OLLAMA_PROVIDER];\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n\nexport function unregisterTransformersModel(args: { agentDir: string; modelId: string }): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) return { ok: false, modelsJsonPath, reason };\n\tconst provider = json.providers[HF_TRANSFORMERS_PROVIDER];\n\tif (!provider?.models) return { ok: true, modelsJsonPath };\n\tconst before = provider.models.length;\n\tprovider.models = provider.models.filter((model) => model.id !== args.modelId);\n\tif (provider.models.length === before) return { ok: true, modelsJsonPath };\n\tif (provider.models.length === 0) {\n\t\tdelete json.providers[HF_TRANSFORMERS_PROVIDER];\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n"]}
@@ -41,6 +41,17 @@ export interface OllamaReleaseAsset {
41
41
  * (e.g. by a future doctor-driven managed install) without touching OllamaRuntime.
42
42
  */
43
43
  export declare function resolveOllamaAsset(plat: string, architecture: string): OllamaReleaseAsset | undefined;
44
+ export interface RuntimeCommandResult {
45
+ ok: boolean;
46
+ stdout: string;
47
+ stderr: string;
48
+ code?: number | null;
49
+ error?: string;
50
+ }
51
+ export type RuntimeCommandRunner = (command: string, args: string[], options?: {
52
+ env?: NodeJS.ProcessEnv;
53
+ onOutput?: (chunk: string) => void;
54
+ }) => Promise<RuntimeCommandResult>;
44
55
  export interface LocalRuntimeDeps {
45
56
  fetchFn?: typeof fetch;
46
57
  spawnFn?: (command: string, args: string[], options: {
@@ -50,9 +61,14 @@ export interface LocalRuntimeDeps {
50
61
  envPath?: string;
51
62
  homeDir?: string;
52
63
  sleepFn?: (ms: number) => Promise<void>;
53
- /** os.platform()/os.arch() equivalents — injectable so asset resolution is testable per platform. */
64
+ /** os.platform()/os.arch() equivalents — injectable so asset/runtime resolution is testable per platform. */
54
65
  platform?: () => string;
55
66
  arch?: () => string;
67
+ /** Runs a runtime-management command (Python venv/pip/download probe). Injectable so tests never
68
+ * install packages or hit the network. */
69
+ runCommand?: RuntimeCommandRunner;
70
+ /** Override for bundled runtime helper scripts, used by tests and source/binary packaging checks. */
71
+ transformersServerScriptPath?: string;
56
72
  /** Node's built-in zstd decompress transform, when THIS runtime's node:zlib has it — undefined
57
73
  * forces the system-zstd fallback. Injectable so tests can force either path deterministically
58
74
  * instead of depending on whatever Node happens to be running the test. */
@@ -67,6 +83,7 @@ export interface LocalRuntimeDeps {
67
83
  error?: string;
68
84
  }>;
69
85
  }
86
+ export declare function resolveTransformersBaseUrl(modelId: string): string;
70
87
  export declare class OllamaRuntime {
71
88
  private readonly _agentDir;
72
89
  private readonly _baseUrl;
@@ -155,4 +172,63 @@ export declare class OllamaRuntime {
155
172
  error?: string;
156
173
  }>;
157
174
  }
175
+ export interface TransformersRuntimeStatus {
176
+ runtimeInstalled: boolean;
177
+ serverUp: boolean;
178
+ baseUrl: string;
179
+ modelId: string;
180
+ venvDir: string;
181
+ cacheDir: string;
182
+ serverScriptPath: string;
183
+ }
184
+ export declare class TransformersRuntime {
185
+ private readonly _agentDir;
186
+ private readonly _modelId;
187
+ private readonly _baseUrl;
188
+ private readonly _fetch;
189
+ private readonly _spawn;
190
+ private readonly _exists;
191
+ private readonly _sleep;
192
+ private readonly _platform;
193
+ private readonly _runCommand;
194
+ private readonly _serverScriptPath;
195
+ private _proc?;
196
+ constructor(args: {
197
+ agentDir: string;
198
+ modelId: string;
199
+ baseUrl?: string;
200
+ deps?: LocalRuntimeDeps;
201
+ });
202
+ get baseUrl(): string;
203
+ get modelId(): string;
204
+ get runtimeDir(): string;
205
+ get venvDir(): string;
206
+ get cacheDir(): string;
207
+ get pythonPath(): string;
208
+ private get serverPort();
209
+ private get serverHost();
210
+ private runtimeEnv;
211
+ private serverUp;
212
+ detect(): Promise<TransformersRuntimeStatus>;
213
+ private pythonCandidates;
214
+ private findPython;
215
+ private torchInstallArgs;
216
+ private runPython;
217
+ installManaged(onProgress?: (status: string) => void): Promise<{
218
+ ok: boolean;
219
+ error?: string;
220
+ }>;
221
+ downloadModel(onProgress?: (status: string) => void): Promise<{
222
+ ok: boolean;
223
+ error?: string;
224
+ }>;
225
+ start(): Promise<{
226
+ started: boolean;
227
+ reason: string;
228
+ }>;
229
+ stop(): {
230
+ stopped: boolean;
231
+ };
232
+ installGuide(): string[];
233
+ }
158
234
  //# sourceMappingURL=local-runtime.d.ts.map