insika 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +295 -0
  3. data/LICENSE +21 -0
  4. data/README.md +136 -2
  5. data/bin/insika +351 -0
  6. data/docs/AGENTS.md +494 -0
  7. data/docs/ARCHITECTURE.md +333 -0
  8. data/docs/BENCHMARK.md +114 -0
  9. data/docs/CHANNELS.md +453 -0
  10. data/docs/CONTEXT.md +100 -0
  11. data/docs/DEPLOY.md +334 -0
  12. data/docs/EMBEDDING.md +194 -0
  13. data/docs/EVALS.md +273 -0
  14. data/docs/LOADTEST.md +231 -0
  15. data/docs/OBSERVABILITY.md +365 -0
  16. data/docs/PLUGINS.md +211 -0
  17. data/docs/REFINEMENT.md +477 -0
  18. data/docs/RELEASING.md +70 -0
  19. data/docs/RUNNING-LOCAL.md +153 -0
  20. data/docs/SANDBOX.md +114 -0
  21. data/docs/SECURITY.md +362 -0
  22. data/docs/SKILLS.md +98 -0
  23. data/docs/TOOLS.md +302 -0
  24. data/docs/WHY.md +137 -0
  25. data/docs/WORKFLOWS.md +225 -0
  26. data/docs/build.md +14 -0
  27. data/docs/index.md +68 -0
  28. data/docs/onboarding/start.md +126 -0
  29. data/docs/operate.md +12 -0
  30. data/docs/ship.md +10 -0
  31. data/docs/understand.md +10 -0
  32. data/lib/insika/agent_file_store.rb +125 -0
  33. data/lib/insika/agent_profile.rb +188 -0
  34. data/lib/insika/allowlist.rb +28 -0
  35. data/lib/insika/baseline_store.rb +74 -0
  36. data/lib/insika/capability/resolved_tool.rb +34 -0
  37. data/lib/insika/capability_registry.rb +112 -0
  38. data/lib/insika/channel_delivery.rb +150 -0
  39. data/lib/insika/channel_registry.rb +30 -0
  40. data/lib/insika/channels/relay.rb +178 -0
  41. data/lib/insika/channels/web/widget.js +283 -0
  42. data/lib/insika/channels/web.rb +211 -0
  43. data/lib/insika/chat_builder.rb +254 -0
  44. data/lib/insika/checkpoint.rb +13 -0
  45. data/lib/insika/checkpoint_store.rb +153 -0
  46. data/lib/insika/coercion.rb +50 -0
  47. data/lib/insika/command.rb +32 -0
  48. data/lib/insika/command_bus.rb +39 -0
  49. data/lib/insika/commands/agent_payload.rb +41 -0
  50. data/lib/insika/commands/approve_action.rb +46 -0
  51. data/lib/insika/commands/cancel_task.rb +33 -0
  52. data/lib/insika/commands/create_agent.rb +54 -0
  53. data/lib/insika/commands/create_session.rb +67 -0
  54. data/lib/insika/commands/delete_agent.rb +33 -0
  55. data/lib/insika/commands/delete_agent_file.rb +50 -0
  56. data/lib/insika/commands/delete_data_tool.rb +33 -0
  57. data/lib/insika/commands/delete_llm_provider.rb +36 -0
  58. data/lib/insika/commands/delete_mcp.rb +30 -0
  59. data/lib/insika/commands/delete_system_file.rb +29 -0
  60. data/lib/insika/commands/gate_refinement.rb +245 -0
  61. data/lib/insika/commands/import_mcp_tools.rb +48 -0
  62. data/lib/insika/commands/import_tools.rb +81 -0
  63. data/lib/insika/commands/memory_add_note.rb +32 -0
  64. data/lib/insika/commands/memory_forget_fact.rb +32 -0
  65. data/lib/insika/commands/memory_put_fact.rb +35 -0
  66. data/lib/insika/commands/pause_task.rb +29 -0
  67. data/lib/insika/commands/resolve_refinement.rb +126 -0
  68. data/lib/insika/commands/restore_agent_file.rb +36 -0
  69. data/lib/insika/commands/restore_data_tool.rb +34 -0
  70. data/lib/insika/commands/restore_system_file.rb +31 -0
  71. data/lib/insika/commands/resume_task.rb +85 -0
  72. data/lib/insika/commands/run_refinement.rb +133 -0
  73. data/lib/insika/commands/send_message.rb +150 -0
  74. data/lib/insika/commands/set_agent_tools.rb +39 -0
  75. data/lib/insika/commands/set_skill_agents.rb +71 -0
  76. data/lib/insika/commands/trigger_workflow.rb +80 -0
  77. data/lib/insika/commands/update_agent.rb +49 -0
  78. data/lib/insika/commands/update_settings.rb +33 -0
  79. data/lib/insika/commands/upsert_llm_provider.rb +34 -0
  80. data/lib/insika/commands/upsert_mcp.rb +32 -0
  81. data/lib/insika/commands/write_agent_file.rb +57 -0
  82. data/lib/insika/commands/write_data_tool.rb +43 -0
  83. data/lib/insika/commands/write_golden.rb +58 -0
  84. data/lib/insika/commands/write_skill.rb +50 -0
  85. data/lib/insika/commands/write_system_file.rb +31 -0
  86. data/lib/insika/config_store.rb +85 -0
  87. data/lib/insika/context/builder.rb +166 -0
  88. data/lib/insika/context/catalog_provider.rb +23 -0
  89. data/lib/insika/context/fragment.rb +19 -0
  90. data/lib/insika/context/priority.rb +29 -0
  91. data/lib/insika/context/provider.rb +19 -0
  92. data/lib/insika/context/providers/memory.rb +60 -0
  93. data/lib/insika/context/providers/prompt.rb +105 -0
  94. data/lib/insika/context/providers/request.rb +32 -0
  95. data/lib/insika/context/providers/session.rb +108 -0
  96. data/lib/insika/context/providers/skill.rb +20 -0
  97. data/lib/insika/context/providers/tool_search.rb +20 -0
  98. data/lib/insika/delegation_store.rb +153 -0
  99. data/lib/insika/doctor.rb +294 -0
  100. data/lib/insika/dsl/definition.rb +55 -0
  101. data/lib/insika/dsl/runtime.rb +379 -0
  102. data/lib/insika/dsl/server_boot.rb +97 -0
  103. data/lib/insika/dsl/system.rb +93 -0
  104. data/lib/insika/dsl/workflow_adapter.rb +59 -0
  105. data/lib/insika/dsl.rb +307 -0
  106. data/lib/insika/edge_limiter.rb +130 -0
  107. data/lib/insika/egress_guard.rb +75 -0
  108. data/lib/insika/env_schema.rb +246 -0
  109. data/lib/insika/errors.rb +145 -0
  110. data/lib/insika/evals/assertions.rb +247 -0
  111. data/lib/insika/evals/baseline.rb +69 -0
  112. data/lib/insika/evals/golden.rb +172 -0
  113. data/lib/insika/evals/judge.rb +225 -0
  114. data/lib/insika/evals/pairwise.rb +178 -0
  115. data/lib/insika/evals/report.rb +115 -0
  116. data/lib/insika/evals/runner.rb +141 -0
  117. data/lib/insika/evals/transport.rb +178 -0
  118. data/lib/insika/event.rb +18 -0
  119. data/lib/insika/event_stream.rb +114 -0
  120. data/lib/insika/executor.rb +1680 -0
  121. data/lib/insika/frontmatter.rb +42 -0
  122. data/lib/insika/golden_store.rb +145 -0
  123. data/lib/insika/hooks.rb +48 -0
  124. data/lib/insika/http_client.rb +63 -0
  125. data/lib/insika/inbound_log.rb +84 -0
  126. data/lib/insika/llm_configurator.rb +99 -0
  127. data/lib/insika/llm_provider_store.rb +83 -0
  128. data/lib/insika/mcp_http_client.rb +67 -0
  129. data/lib/insika/mcp_store.rb +115 -0
  130. data/lib/insika/mcp_tool_ingestor.rb +143 -0
  131. data/lib/insika/memory_store.rb +93 -0
  132. data/lib/insika/message_origin.rb +76 -0
  133. data/lib/insika/middleware.rb +36 -0
  134. data/lib/insika/model_policy.rb +52 -0
  135. data/lib/insika/model_resolver.rb +176 -0
  136. data/lib/insika/model_selection.rb +114 -0
  137. data/lib/insika/onboarding.rb +208 -0
  138. data/lib/insika/outbox_store.rb +166 -0
  139. data/lib/insika/overlay_tool_registry.rb +103 -0
  140. data/lib/insika/pack.rb +102 -0
  141. data/lib/insika/pack_importer.rb +121 -0
  142. data/lib/insika/pending_action_store.rb +120 -0
  143. data/lib/insika/plugin/loader.rb +356 -0
  144. data/lib/insika/plugin.rb +35 -0
  145. data/lib/insika/policy/engine.rb +83 -0
  146. data/lib/insika/policy/policy.rb +120 -0
  147. data/lib/insika/policy_registry.rb +23 -0
  148. data/lib/insika/profile_source.rb +137 -0
  149. data/lib/insika/prompt_catalog.rb +61 -0
  150. data/lib/insika/queue_policy.rb +167 -0
  151. data/lib/insika/recovery.rb +127 -0
  152. data/lib/insika/refinement/candidate.rb +159 -0
  153. data/lib/insika/refinement/evidence_collector.rb +371 -0
  154. data/lib/insika/refinement/gate.rb +234 -0
  155. data/lib/insika/refinement/panel.rb +222 -0
  156. data/lib/insika/refinement/proposer.rb +262 -0
  157. data/lib/insika/refinement_store.rb +295 -0
  158. data/lib/insika/registry.rb +59 -0
  159. data/lib/insika/safety/config.rb +109 -0
  160. data/lib/insika/safety/detectors.rb +176 -0
  161. data/lib/insika/safety/factory.rb +102 -0
  162. data/lib/insika/safety/input_guardrail.rb +87 -0
  163. data/lib/insika/safety/moderator.rb +86 -0
  164. data/lib/insika/safety/output_filter.rb +79 -0
  165. data/lib/insika/safety/output_validator.rb +101 -0
  166. data/lib/insika/safety/safe_responses.rb +47 -0
  167. data/lib/insika/sandbox/boundary.rb +93 -0
  168. data/lib/insika/sandbox/docker.rb +74 -0
  169. data/lib/insika/sandbox/local.rb +33 -0
  170. data/lib/insika/sandbox/runner.rb +80 -0
  171. data/lib/insika/sandbox.rb +85 -0
  172. data/lib/insika/schema_guard.rb +147 -0
  173. data/lib/insika/secret_masking.rb +34 -0
  174. data/lib/insika/server/a2a/agent_card.rb +27 -0
  175. data/lib/insika/server/a2a/app.rb +112 -0
  176. data/lib/insika/server/a2a/client.rb +101 -0
  177. data/lib/insika/server/a2a/errors.rb +32 -0
  178. data/lib/insika/server/a2a/http.rb +42 -0
  179. data/lib/insika/server/a2a/message.rb +27 -0
  180. data/lib/insika/server/a2a/protocol.rb +45 -0
  181. data/lib/insika/server/a2a/remotes.rb +25 -0
  182. data/lib/insika/server/a2a/task_projection.rb +40 -0
  183. data/lib/insika/server/admin_auth.rb +29 -0
  184. data/lib/insika/server/app.rb +850 -0
  185. data/lib/insika/server/boot.rb +119 -0
  186. data/lib/insika/server/rack_app.rb +110 -0
  187. data/lib/insika/server/responses.rb +155 -0
  188. data/lib/insika/server/sse_body.rb +96 -0
  189. data/lib/insika/session_actor.rb +162 -0
  190. data/lib/insika/session_store.rb +143 -0
  191. data/lib/insika/settings_store.rb +154 -0
  192. data/lib/insika/shutdown.rb +125 -0
  193. data/lib/insika/skill_catalog.rb +113 -0
  194. data/lib/insika/skill_store.rb +79 -0
  195. data/lib/insika/steer_injector.rb +110 -0
  196. data/lib/insika/store.rb +52 -0
  197. data/lib/insika/stores/memory.rb +123 -0
  198. data/lib/insika/stores/sqlite.rb +183 -0
  199. data/lib/insika/studio/app.rb +1571 -0
  200. data/lib/insika/studio/assets/dist/application.css +1 -0
  201. data/lib/insika/studio/assets/dist/application.js +69 -0
  202. data/lib/insika/studio/forms.rb +340 -0
  203. data/lib/insika/studio/nav_icons.rb +31 -0
  204. data/lib/insika/studio/views/_message.erb +44 -0
  205. data/lib/insika/studio/views/agent_detail.erb +285 -0
  206. data/lib/insika/studio/views/agents.erb +63 -0
  207. data/lib/insika/studio/views/approvals.erb +41 -0
  208. data/lib/insika/studio/views/chats.erb +34 -0
  209. data/lib/insika/studio/views/evals.erb +83 -0
  210. data/lib/insika/studio/views/home.erb +72 -0
  211. data/lib/insika/studio/views/layout.erb +94 -0
  212. data/lib/insika/studio/views/login.erb +17 -0
  213. data/lib/insika/studio/views/mcp.erb +91 -0
  214. data/lib/insika/studio/views/not_found.erb +5 -0
  215. data/lib/insika/studio/views/playground.erb +47 -0
  216. data/lib/insika/studio/views/refinement.erb +234 -0
  217. data/lib/insika/studio/views/session.erb +62 -0
  218. data/lib/insika/studio/views/settings.erb +173 -0
  219. data/lib/insika/studio/views/skills.erb +86 -0
  220. data/lib/insika/studio/views/system_files.erb +65 -0
  221. data/lib/insika/studio/views/task.erb +105 -0
  222. data/lib/insika/studio/views/tasks.erb +33 -0
  223. data/lib/insika/studio/views/tool_edit.erb +107 -0
  224. data/lib/insika/studio/views/tools.erb +89 -0
  225. data/lib/insika/subagent_graph.rb +96 -0
  226. data/lib/insika/system_file_store.rb +96 -0
  227. data/lib/insika/task_actor.rb +128 -0
  228. data/lib/insika/task_store.rb +250 -0
  229. data/lib/insika/telemetry/pricing.rb +104 -0
  230. data/lib/insika/telemetry/recorder.rb +228 -0
  231. data/lib/insika/telemetry.rb +127 -0
  232. data/lib/insika/testing/store_contract.rb +270 -0
  233. data/lib/insika/token_estimator.rb +16 -0
  234. data/lib/insika/tool_assembly.rb +140 -0
  235. data/lib/insika/tool_catalog.rb +89 -0
  236. data/lib/insika/tool_definition.rb +518 -0
  237. data/lib/insika/tool_envelope.rb +140 -0
  238. data/lib/insika/tool_manifest.rb +218 -0
  239. data/lib/insika/tool_registry.rb +21 -0
  240. data/lib/insika/tool_store.rb +135 -0
  241. data/lib/insika/tool_trace_store.rb +92 -0
  242. data/lib/insika/tools/a2a_remote.rb +48 -0
  243. data/lib/insika/tools/agent_enum.rb +68 -0
  244. data/lib/insika/tools/concurrency.rb +54 -0
  245. data/lib/insika/tools/data_defined_tool.rb +220 -0
  246. data/lib/insika/tools/load_skill.rb +41 -0
  247. data/lib/insika/tools/remember.rb +53 -0
  248. data/lib/insika/tools/subagent.rb +75 -0
  249. data/lib/insika/tools/subagents.rb +77 -0
  250. data/lib/insika/tools/tool_search.rb +94 -0
  251. data/lib/insika/turn_output.rb +139 -0
  252. data/lib/insika/turn_state.rb +158 -0
  253. data/lib/insika/turn_timing.rb +56 -0
  254. data/lib/insika/usage_ledger.rb +47 -0
  255. data/lib/insika/version.rb +3 -1
  256. data/lib/insika/wiring/graph.rb +198 -0
  257. data/lib/insika/workflow.rb +185 -0
  258. data/lib/insika/workflow_registry.rb +33 -0
  259. data/lib/insika.rb +203 -4
  260. metadata +395 -8
@@ -0,0 +1,254 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module Insika
6
+ # Assembles the turn's chat (pipeline stages 5-7): instructions, eager/deferred
7
+ # tool partition, system tools (tool_search/load_skill/remember),
8
+ # history and callbacks. Extracted from the Executor so it can coordinate the
9
+ # pipeline without also carrying the RubyLLM glue.
10
+ #
11
+ # The Executor creates the chat (stage 6, the RubyLLM boundary) and passes it
12
+ # here to be configured; event numbering (monotonic seq per task) stays in the
13
+ # Executor, injected as the `emit` callable.
14
+ class ChatBuilder
15
+ def initialize(tool_registry:, skill_catalog:, checkpoint_store:, event_stream:,
16
+ hooks:, tool_catalog: nil, memory_store: nil, subagent_runner: nil)
17
+ @tool_registry = tool_registry
18
+ @skill_catalog = skill_catalog
19
+ @checkpoint_store = checkpoint_store
20
+ @event_stream = event_stream
21
+ @hooks = hooks
22
+ @tool_catalog = tool_catalog
23
+ @memory_store = memory_store
24
+ # RFC-0010: the object exposing #run_subagent (the Executor). nil = the
25
+ # spawn_subagent system tool is never wired (parity for a builder used
26
+ # without delegation, e.g. some unit stubs).
27
+ @subagent_runner = subagent_runner
28
+ end
29
+
30
+ # Configures an already-created chat with the context (stage 2) and the
31
+ # Resolution (stage 3), seeds the history and wires the callbacks. `emit` is
32
+ # the Executor's emitter (seq+task correlation), called as emit.call(type,
33
+ # data). The system tools (Tools::ToolSearch/LoadSkill/Remember) were already
34
+ # lazy-loaded by Executor#create_chat before reaching here.
35
+ def assemble(chat, state, emit:)
36
+ configure_chat(chat, state)
37
+ seed_history(chat, Array(state.context.history))
38
+ wire_callbacks(chat, state, emit)
39
+ chat
40
+ end
41
+
42
+ # Assembles the chat with the context (stage 2) and the Resolution's tools (stage 3).
43
+ def configure_chat(chat, state)
44
+ system = state.context.system.to_s
45
+ apply_instructions(chat, system, state) unless system.empty?
46
+
47
+ tools = Array(state.allowed_tools).dup
48
+
49
+ # Tool Search: the partition only runs with @tool_catalog present (parity
50
+ # when nil — the `&&` short-circuits before reading `.name`).
51
+ # `deferred_allowed` = allowed_tools ∩ tools_deferred. The <available_tools>
52
+ # catalog comes from Context::Providers::ToolSearch (stage 2); here we only
53
+ # decide chat.tools.
54
+ deferred_allowed = if @tool_catalog
55
+ Array(state.profile.tools_deferred).map(&:to_s) &
56
+ tools.map { |t| t.name.to_s }
57
+ else
58
+ []
59
+ end
60
+
61
+ unless deferred_allowed.empty?
62
+ tools.reject! { |t| deferred_allowed.include?(t.name.to_s) }
63
+ # a system tool (outside the allowlist), like load_skill — never enveloped.
64
+ tools << Tools::ToolSearch.new(@tool_catalog, deferred_allowed, chat,
65
+ tool_registry: @tool_registry,
66
+ checkpoint_store: @checkpoint_store,
67
+ event_stream: @event_stream, state: state)
68
+ end
69
+
70
+ # load_skill is a system default (outside the allowlist), otherwise
71
+ # progressive disclosure breaks. allowed_skills comes from the Resolution
72
+ # (policy).
73
+ skill_names = Array(state.allowed_skills).map { |s| s.respond_to?(:name) ? s.name : s.to_s }
74
+ tools << Tools::LoadSkill.new(@skill_catalog, skill_names) unless skill_names.empty?
75
+
76
+ # remember is the memory-write system tool — wired only with
77
+ # @memory_store present AND profile.memory (a double gate). Never enveloped.
78
+ if @memory_store && state.profile.memory
79
+ tools << Tools::Remember.new(@memory_store, state.tenant,
80
+ event_stream: @event_stream, state: state)
81
+ end
82
+
83
+ # spawn_subagent is the delegation system tool (RFC-0010) — wired only with a
84
+ # runner present AND profile.subagents non-empty (a double gate, like
85
+ # remember). Never enveloped: in the synchronous mode the child lives in the
86
+ # parent's envelope. The runtime gate on WHICH agent is spawnable is the
87
+ # parent's subagents allowlist, enforced in Executor#run_subagent.
88
+ if @subagent_runner && !Array(state.profile.subagents).empty?
89
+ tools << Tools::Subagent.new(runner: @subagent_runner, state: state)
90
+ # ...and its parallel sibling (RFC-0010 §A): fan-out N children at once.
91
+ tools << Tools::Subagents.new(runner: @subagent_runner, state: state)
92
+ end
93
+
94
+ unless tools.empty?
95
+ # Item 30: the ONLY place the gem is told to run tool calls in parallel.
96
+ # `:fibers` is not a preference but the only admissible mode — `:threads`
97
+ # breaks ToolEnvelope's `Async::Task.current.with_timeout`, the SQLite
98
+ # store's fiber semaphore, and the turn's own durability (mailbox,
99
+ # approvals, cancellation are all expressed in fiber terms). The number
100
+ # the operator configured is OUR cap (D4, ToolAssembly#install_tool_gate);
101
+ # the gem has none.
102
+ if tool_concurrency_for(state)
103
+ chat.with_tools(*tools, concurrency: :fibers)
104
+ else
105
+ chat.with_tools(*tools)
106
+ end
107
+ end
108
+
109
+ chat
110
+ end
111
+
112
+ # The turn's effective tool concurrency (nil = serial), plus the ONE thing the
113
+ # gate owes the operator: when the profile asked for parallel tool calls and
114
+ # this turn silently cannot have them (D3 — an approval-required tool would
115
+ # deadlock two fibers on the single per-task mailbox), say so once. Otherwise
116
+ # the speedup just vanishes with no reason given. The rule itself lives in
117
+ # TurnState; a state predating those readers (a unit stub) means off.
118
+ def tool_concurrency_for(state)
119
+ return nil unless state.respond_to?(:tool_concurrency)
120
+
121
+ effective = state.tool_concurrency
122
+ return effective if effective
123
+
124
+ requested = state.requested_tool_concurrency
125
+ warn_tool_concurrency_gated(state, requested) if requested
126
+ nil
127
+ end
128
+
129
+ def warn_tool_concurrency_gated(state, requested)
130
+ gated = Array(state.requires_approval)
131
+ @event_stream.emit(Insika::Event.new(
132
+ type: :provider_warning,
133
+ data: { provider: "tool_concurrency",
134
+ message: "parallel tool calls (#{requested}) disabled for this turn: " \
135
+ "#{gated.size} tool(s) require approval (#{gated.join(', ')})" },
136
+ meta: { task_id: state.task&.id, at: Time.now.utc.iso8601 }
137
+ ))
138
+ end
139
+
140
+ # §11 R3: opt-in Anthropic prompt caching. When the agent enables
141
+ # prompt_caching AND the resolved provider is Anthropic, wrap the system in
142
+ # the provider's native Content helper with cache: true — ONE breakpoint at
143
+ # the END of the system block. By Anthropic's prefix order
144
+ # (tools -> system -> messages), a breakpoint on the last system block caches
145
+ # tools + system together and is immune to history eviction (messages come
146
+ # after it). RubyLLM::Content::Raw is Anthropic-specific: build_system_content
147
+ # emits its blocks verbatim, so the cache_control rides along.
148
+ #
149
+ # Any other case (caching off, or a non-Anthropic provider) uses the plain
150
+ # string — OpenAI caches its prefix on its own; the Raw shape would confuse
151
+ # non-Anthropic providers. The gem only supports MANUAL caching, and only for
152
+ # Anthropic.
153
+ #
154
+ # PRE-AUDIT (why this is opt-in): the system must be BYTE-STABLE between turns
155
+ # for a read hit. A context provider that injects volatile content into
156
+ # :system (timestamps, per-turn data) makes every turn a paid cache WRITE
157
+ # with no hit — worse than off. Enable only for stable-system agents.
158
+ def apply_instructions(chat, system, state)
159
+ if state.profile.prompt_caching && anthropic_provider?(chat)
160
+ chat.with_instructions(RubyLLM::Providers::Anthropic::Content.new(system, cache: true))
161
+ else
162
+ chat.with_instructions(system)
163
+ end
164
+ end
165
+
166
+ # The RESOLVED provider (chat.model.provider is the slug string, e.g.
167
+ # "anthropic"), authoritative even when the agent left provider nil and
168
+ # RubyLLM inferred it from the model id. Any surface without a model (fakes,
169
+ # a provider that raises) -> false: caching silently stays off.
170
+ def anthropic_provider?(chat)
171
+ chat.respond_to?(:model) && chat.model && chat.model.provider.to_s == "anthropic"
172
+ rescue StandardError
173
+ false
174
+ end
175
+
176
+ # History comes from the context/checkpoint. The {role:, content:} shape
177
+ # tolerates string keys (JSON from the stores). `flatten(1)` dissolves the
178
+ # Session provider's "eviction units" (an assistant+tool_results cycle grouped
179
+ # as one Array, §11 R1) back into a flat message stream.
180
+ #
181
+ # tool_calls / tool_call_id are rehydrated ONLY when present, so a message
182
+ # without them keeps the 2-arg shape the specs' FakeChat expects (no unknown
183
+ # keyword). This is what lets the model SEE the tools it already called.
184
+ def seed_history(chat, messages)
185
+ Array(messages).flatten(1).each do |m|
186
+ attrs = { role: (m[:role] || m["role"]).to_sym, content: m[:content] || m["content"] }
187
+ tool_calls = m[:tool_calls] || m["tool_calls"]
188
+ tool_call_id = m[:tool_call_id] || m["tool_call_id"]
189
+ attrs[:tool_calls] = rehydrate_tool_calls(tool_calls) if tool_calls && !Array(tool_calls).empty?
190
+ attrs[:tool_call_id] = tool_call_id if tool_call_id
191
+ chat.add_message(**attrs)
192
+ end
193
+ end
194
+
195
+ # [{id,name,arguments}] (string|symbol keys) -> {id => RubyLLM::ToolCall}, the
196
+ # shape RubyLLM seeds an assistant message with. Called only when the gem is
197
+ # already loaded (create_chat required it before assemble).
198
+ def rehydrate_tool_calls(list)
199
+ Array(list).each_with_object({}) do |tc, acc|
200
+ id = (tc[:id] || tc["id"]).to_s
201
+ acc[id] = RubyLLM::ToolCall.new(
202
+ id: id, name: (tc[:name] || tc["name"]).to_s,
203
+ arguments: tc[:arguments] || tc["arguments"] || {}
204
+ )
205
+ end
206
+ end
207
+
208
+ # RubyLLM's additive callbacks become events. load_skill becomes
209
+ # :skill_activated. Adds the max_tool_calls counter: the loop is RubyLLM's;
210
+ # here we only count and abort.
211
+ def wire_callbacks(chat, state, emit)
212
+ # Per-TURN counter: safe as a closure local even under concurrent tool calls
213
+ # (MRI fibers do not preempt between the read and the write). The per-CALL
214
+ # correlation is NOT — it lives in fiber storage behind TurnState, because
215
+ # each call gets its own fiber once tool concurrency is on.
216
+ tool_calls = 0
217
+ max_tool_calls = state.profile.limits[:max_tool_calls] || 50
218
+
219
+ chat.before_tool_call do |tool_call|
220
+ # call<->decorator correlation (side-effects/skip) — 1st line.
221
+ state.current_tool_call = tool_call
222
+ # max_tool_calls guard-rail: stays inline (not as a registered hook)
223
+ # because Hooks is shared across turns and has no unregister.
224
+ tool_calls += 1
225
+ if tool_calls > max_tool_calls
226
+ raise Insika::TimeoutError.new("tool call limit exceeded (#{max_tool_calls})",
227
+ stage: :tool_limit)
228
+ end
229
+
230
+ # :tool pair: RubyLLM's callbacks are additive — the altered subject
231
+ # feeds later hooks and the events, but does not rewrite the call the
232
+ # model executes. A hook exception here aborts the turn.
233
+ tool_call = @hooks.run_before(:tool, tool_call)
234
+
235
+ # The name of the (possibly hook-altered) subject, for the :tool_result
236
+ # label. Also fiber-scoped: as a closure local it belonged to the TURN, so
237
+ # under concurrency `after_tool_result` labelled every result with whichever
238
+ # call started last.
239
+ state.current_tool_name = tool_call.name.to_s
240
+ if state.current_tool_name == "load_skill"
241
+ args = tool_call.arguments || {}
242
+ emit.call(:skill_activated, { name: args["name"] || args[:name] })
243
+ else
244
+ emit.call(:tool_call, { name: tool_call.name, arguments: tool_call.arguments })
245
+ end
246
+ end
247
+
248
+ chat.after_tool_result do |result|
249
+ result = @hooks.run_after(:tool, result)
250
+ emit.call(:tool_result, { name: state.current_tool_name, result: result.to_s })
251
+ end
252
+ end
253
+ end
254
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insika
4
+ # Per-turn snapshot. The checkpoint of
5
+ # turn n holds the state AT THE START of turn n — resuming = re-executing the
6
+ # whole turn n. `messages` is the MATERIALIZED transcript (not a cursor): the
7
+ # checkpoint is self-contained and resumption does not depend on the Session Store.
8
+ #
9
+ # `completed_side_effects`: ids of non-idempotent tool calls already completed
10
+ # within the turn (resumption answers them with "already_executed").
11
+ Checkpoint = Data.define(:task_id, :turn, :session_id, :agent_id,
12
+ :messages, :completed_side_effects, :created_at)
13
+ end
@@ -0,0 +1,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module Insika
6
+ # Domain store for checkpoints. A per-turn snapshot written
7
+ # in an ALL-OR-NOTHING transaction (invariant: a checkpoint is either fully
8
+ # valid or does not exist), a record of non-idempotent side effects in a spill
9
+ # key during the turn, and `prune` to bound growth.
10
+ #
11
+ # Two key families in the "checkpoints" scope:
12
+ # "checkpoint:<task_id>:turn:<n>" -> Checkpoint JSON
13
+ # "sideeffects:<task_id>:turn:<n>" -> ["tool_call_id", ...] (spill key)
14
+ #
15
+ # The spill key exists because the turn's checkpoint does not exist yet when
16
+ # the tool calls run (it is only saved at stage 8): it is written BEFORE the
17
+ # tool result goes back to the model, and the following `save` consolidates it
18
+ # into `completed_side_effects` and deletes it in the SAME transaction.
19
+ class CheckpointStore
20
+ include Coercion
21
+
22
+ SCOPE = "checkpoints"
23
+
24
+ def initialize(store:)
25
+ @store = store
26
+ end
27
+
28
+ # -> Checkpoint (with the consolidated side-effect list). ALWAYS in a
29
+ # transaction. Order: validate monotonicity -> consolidate the previous
30
+ # turn's spill key -> write the checkpoint -> delete the absorbed spill key.
31
+ # Any exception in the middle -> full rollback (neither a partial checkpoint
32
+ # nor a lost spill key).
33
+ def save(checkpoint)
34
+ @store.transaction do
35
+ current = latest(checkpoint.task_id)
36
+ if current && current.turn >= checkpoint.turn
37
+ raise ArgumentError,
38
+ "checkpoint with non-monotonic turn: #{checkpoint.turn} <= #{current.turn}"
39
+ end
40
+
41
+ # Stage 8 of turn n saves turn n+1's checkpoint:
42
+ # the spill key to absorb is that of the turn that just executed (n).
43
+ spill_key = sideeffects_key(checkpoint.task_id, checkpoint.turn - 1)
44
+ spilled = @store.get(SCOPE, spill_key) || []
45
+ consolidated = Array(checkpoint.completed_side_effects).map(&:to_s) | spilled
46
+
47
+ record = deep_stringify(checkpoint.to_h)
48
+ record["completed_side_effects"] = consolidated
49
+ record["created_at"] ||= timestamp
50
+ @store.set(SCOPE, checkpoint_key(checkpoint.task_id, checkpoint.turn), record)
51
+ @store.delete(SCOPE, spill_key)
52
+
53
+ to_checkpoint(record)
54
+ end
55
+ end
56
+
57
+ # -> Checkpoint | nil (highest turn). NUMERIC ordering: `list` sorts
58
+ # lexicographically and "turn:9" > "turn:10" — parse n as an Integer.
59
+ def latest(task_id)
60
+ turns = checkpoint_turns(task_id)
61
+ return nil if turns.empty?
62
+
63
+ find(task_id, turn: turns.max)
64
+ end
65
+
66
+ # -> Checkpoint | nil
67
+ def find(task_id, turn:)
68
+ record = @store.get(SCOPE, checkpoint_key(task_id, turn))
69
+ record && to_checkpoint(record)
70
+ end
71
+
72
+ # -> nil; idempotent (recording twice = one entry). In a transaction
73
+ # (written before the tool goes back to the model).
74
+ def record_side_effect(task_id, turn:, tool_call_id:)
75
+ @store.transaction do
76
+ key = sideeffects_key(task_id, turn)
77
+ ids = @store.get(SCOPE, key) || []
78
+ id = tool_call_id.to_s
79
+ @store.set(SCOPE, key, ids + [id]) unless ids.include?(id)
80
+ end
81
+ nil
82
+ end
83
+
84
+ # -> [tool_call_id] = spill key ∪ checkpoint of the same turn.
85
+ # Covers both places where an id may live during the cycle; since
86
+ # tool_call_id is globally unique, the union never causes an improper skip.
87
+ def side_effects(task_id, turn:)
88
+ spilled = @store.get(SCOPE, sideeffects_key(task_id, turn)) || []
89
+ from_checkpoint = find(task_id, turn: turn)&.completed_side_effects || []
90
+ spilled | from_checkpoint
91
+ end
92
+
93
+ # -> void. Keeps the `keep` checkpoints with the highest turn (numeric); deletes the
94
+ # rest. Also clears spill keys of turns strictly smaller than the smallest
95
+ # kept turn (unreachable garbage after consolidation). In a transaction
96
+ # so it never leaves a partial prune. No-op if there are <= keep checkpoints.
97
+ def prune(task_id, keep: 1)
98
+ @store.transaction do
99
+ turns = checkpoint_turns(task_id).sort
100
+ next if turns.size <= keep
101
+
102
+ kept = turns.last(keep)
103
+ smallest_kept = kept.first
104
+ (turns - kept).each { |n| @store.delete(SCOPE, checkpoint_key(task_id, n)) }
105
+ sideeffect_turns(task_id).each do |n|
106
+ @store.delete(SCOPE, sideeffects_key(task_id, n)) if n < smallest_kept
107
+ end
108
+ end
109
+ nil
110
+ end
111
+
112
+ private
113
+
114
+ def checkpoint_key(task_id, turn)
115
+ "checkpoint:#{task_id}:turn:#{turn}"
116
+ end
117
+
118
+ def sideeffects_key(task_id, turn)
119
+ "sideeffects:#{task_id}:turn:#{turn}"
120
+ end
121
+
122
+ def checkpoint_turns(task_id)
123
+ @store.list(SCOPE, "checkpoint:#{task_id}:turn:").map { |k| turn_of(k) }
124
+ end
125
+
126
+ def sideeffect_turns(task_id)
127
+ @store.list(SCOPE, "sideeffects:#{task_id}:turn:").map { |k| turn_of(k) }
128
+ end
129
+
130
+ # n is the last segment of the key "...:turn:<n>"; parse it as an Integer.
131
+ def turn_of(key)
132
+ key.split(":").last.to_i
133
+ end
134
+
135
+ # Materializes at the edge: `turn` as an Integer; the other fields as they come from the
136
+ # backend (string keys in `messages`).
137
+ def to_checkpoint(record)
138
+ Checkpoint.new(
139
+ task_id: record["task_id"],
140
+ turn: record["turn"].to_i,
141
+ session_id: record["session_id"],
142
+ agent_id: record["agent_id"],
143
+ messages: record["messages"],
144
+ completed_side_effects: record["completed_side_effects"],
145
+ created_at: record["created_at"]
146
+ )
147
+ end
148
+
149
+ def timestamp
150
+ Time.now.utc.iso8601
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insika
4
+ # Shared coercions at the input/persistence boundary. They used to live
5
+ # copied in each store/handler; a single home keeps them from drifting.
6
+ module Coercion
7
+ module_function
8
+
9
+ # Present string or nil: nil and blank (incl. whitespace-only) become nil;
10
+ # everything else becomes a stripped String.
11
+ def presence(str)
12
+ s = str.to_s.strip
13
+ s.empty? ? nil : s
14
+ end
15
+
16
+ # nil or blank (incl. whitespace-only) -> true.
17
+ def blank?(value) = value.nil? || value.to_s.strip.empty?
18
+
19
+ # Inverse of blank? — a usable, non-empty value.
20
+ def present?(value) = !blank?(value)
21
+
22
+ # Bytes that come from outside the engine (sockets, pipes, subprocesses)
23
+ # arrive tagged BINARY, or as UTF-8 carrying invalid sequences. Both break
24
+ # `JSON.generate` the moment the text has an accent or an emoji — today a
25
+ # warning ("UTF-8 string passed as BINARY"), an exception from json 3.0 — and
26
+ # that text ends up in a transcript, an event and an SSE frame. Reinterprets
27
+ # the bytes as UTF-8 (the wire encoding of every source we read) and scrubs
28
+ # what is not valid, so what crosses the boundary is always serializable.
29
+ def utf8(str)
30
+ s = str.to_s
31
+ s = s.dup.force_encoding(Encoding::UTF_8) unless s.encoding == Encoding::UTF_8
32
+ s.valid_encoding? ? s : s.scrub
33
+ end
34
+
35
+ # Normalizes keys and Symbols to String recursively (the stores' JSON model
36
+ # has no Symbol). Hash -> keys and values; Array -> elements.
37
+ def deep_stringify(obj)
38
+ case obj
39
+ when Hash
40
+ obj.each_with_object({}) { |(k, v), acc| acc[k.to_s] = deep_stringify(v) }
41
+ when Array
42
+ obj.map { |v| deep_stringify(v) }
43
+ when Symbol
44
+ obj.to_s
45
+ else
46
+ obj
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "time"
5
+
6
+ module Insika
7
+ # Every mutating interaction becomes a Command. Shared shape:
8
+ # type: Symbol (:create_session, :send_message, :trigger_workflow,
9
+ # :cancel_task, :resume_task)
10
+ # payload: Hash validated by the handler
11
+ # meta: { command_id:, tenant:, transport:, issued_at: }
12
+ #
13
+ # `Command` does not validate payload (that's the handler's job) and does not
14
+ # know about the bus.
15
+ Command = Data.define(:type, :payload, :meta) do
16
+ # Factory that fills in the meta defaults. `type` is
17
+ # normalized to Symbol; a nil `payload` becomes {} (the handler decides
18
+ # whether required fields are missing).
19
+ def self.build(type, payload = {}, transport: :internal, tenant: nil)
20
+ new(
21
+ type: type.to_sym,
22
+ payload: payload || {},
23
+ meta: {
24
+ command_id: SecureRandom.uuid,
25
+ tenant: tenant,
26
+ transport: transport,
27
+ issued_at: Time.now.utc.iso8601
28
+ }
29
+ )
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insika
4
+ # Routes Commands to handlers registered by the composition root.
5
+ # The bus does NOT distinguish control Commands (synchronous response) from
6
+ # turn Commands (immediate `{task_id:}`) — that is the handler's job; the bus
7
+ # only routes.
8
+ #
9
+ # No lock/mutex: one reactor, cooperative fibers; `dispatch`
10
+ # does no IO of its own.
11
+ class CommandBus
12
+ # Handlers receive their dependencies in their own constructor and emit on
13
+ # their own — the bus only routes.
14
+ def initialize
15
+ @handlers = {}
16
+ end
17
+
18
+ # handler: any object responding to #call(command). Re-registering the
19
+ # same type overwrites (last wins — the composition root is the only
20
+ # caller).
21
+ def register(type, handler)
22
+ @handlers[type.to_sym] = handler
23
+ end
24
+
25
+ # Introspection for the composition roots / graph specs: which command
26
+ # types the bus can route. Read-only; does not expose the handlers.
27
+ def registered?(type) = @handlers.key?(type.to_sym)
28
+ def types = @handlers.keys
29
+
30
+ # -> the handler's result. Unregistered type -> synchronous ValidationError,
31
+ # no Task created (never KeyError/NoMethodError).
32
+ def dispatch(command)
33
+ handler = @handlers[command.type]
34
+ raise Insika::ValidationError, "unknown command: #{command.type}" if handler.nil?
35
+
36
+ handler.call(command)
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insika
4
+ module Commands
5
+ # Shared normalization for the agent-authoring payload.
6
+ # The transport delivers string keys (JSON); internal dispatch uses
7
+ # symbols. Here: symbolize the top level, keep only the fields buildable by
8
+ # AgentProfile, and re-symbolize the fields the runtime consumes as symbols
9
+ # (provider, policies, limits keys) — same rule as StoredProfileSource.
10
+ module AgentPayload
11
+ # Fields accepted by AgentProfile.build (order irrelevant).
12
+ FIELDS = %i[id model provider base_prompt prompt_files tools_allow tools_deny
13
+ tools_allow_groups skills context_providers workflows_allow policies
14
+ prompt_refs limits approvals_required capabilities subagents tools_deferred
15
+ memory params model_policy guardrails refinement capabilities_declared
16
+ edge_stream metadata].freeze
17
+
18
+ module_function
19
+
20
+ # payload (string|symbol keys) -> Hash of attrs ready for AgentProfile.build.
21
+ def attrs(payload)
22
+ h = symbolize(payload)
23
+ out = {}
24
+ FIELDS.each { |f| out[f] = h[f] if h.key?(f) }
25
+ out[:provider] = presence(out[:provider])&.to_sym if out.key?(:provider)
26
+ out[:policies] = Array(out[:policies]).map(&:to_sym) if out.key?(:policies)
27
+ out[:limits] = out[:limits].transform_keys(&:to_sym) if out[:limits].is_a?(Hash)
28
+ # generation params (v2, §10) consumed by symbol key (temperature/max_tokens/thinking).
29
+ out[:params] = out[:params].transform_keys(&:to_sym) if out[:params].is_a?(Hash)
30
+ out
31
+ end
32
+
33
+ def symbolize(payload)
34
+ (payload || {}).each_with_object({}) { |(k, v), acc| acc[k.to_sym] = v }
35
+ end
36
+
37
+ # Stable name used by the handlers; the rule lives in Insika::Coercion.
38
+ def presence(str) = Insika::Coercion.presence(str)
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module Insika
6
+ module Commands
7
+ # Control command: the operator resolves a pending action
8
+ # (human-in-the-loop). Resolves the PendingAction in the store (durable source
9
+ # of truth) and WAKES the turn suspended on :waiting by posting :approval to the
10
+ # live fiber. Order matters: RESOLVE before posting — when the await wakes, the
11
+ # store already has the decision (request_approval re-reads it from there). Crash-safe:
12
+ # with no live fiber the post is a no-op; recovery re-executes and uses the durable decision.
13
+ #
14
+ # Payload `{ pending_id:, decision: "approved"|"rejected", operator?: }`.
15
+ # -> resolved PendingAction.
16
+ class ApproveAction
17
+ def initialize(pending_action_store:, executor:, event_stream:)
18
+ @pending_action_store = pending_action_store
19
+ @executor = executor
20
+ @event_stream = event_stream
21
+ end
22
+
23
+ def call(command)
24
+ p = command.payload
25
+ pending_id = (p[:pending_id] || p["pending_id"]).to_s
26
+ decision = (p[:decision] || p["decision"]).to_s
27
+ raise Insika::ValidationError, "pending_id is required" if pending_id.empty?
28
+
29
+ # operator: from the operator's auth (Control UI) via payload; nil ok.
30
+ operator = p[:operator] || p["operator"] || command.meta[:operator]
31
+
32
+ # resolve() validates the decision and the state (:pending); NotFound if absent.
33
+ resolved = @pending_action_store.resolve(pending_id, decision: decision, operator: operator)
34
+
35
+ @executor.approve(resolved.task_id) # wakes the live fiber (no-op if it crashed)
36
+ @event_stream.emit(Insika::Event.new(
37
+ type: :approval_resolved,
38
+ data: { pending_id: pending_id, decision: resolved.status,
39
+ task_id: resolved.task_id, resolved_by: operator },
40
+ meta: { task_id: resolved.task_id, at: Time.now.utc.iso8601 }
41
+ ))
42
+ resolved
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insika
4
+ module Commands
5
+ # Control command: posts `:cancel` to the Task's in-process mailbox
6
+ # and responds synchronously. Payload `{ task_id: String }` -> returns Task.
7
+ #
8
+ # Cancellation is COOPERATIVE: the one that transitions the status is the
9
+ # task's fiber when it drains the mailbox — NEVER this handler. Cancelling a task with no
10
+ # live fiber (terminal or orphaned) is an idempotent no-op.
11
+ class CancelTask
12
+ # executor: object with #cancel(task_id) — the real implementation is
13
+ # `@running[task_id]&.post(:cancel)`; here it's a contract (duck type).
14
+ def initialize(task_store:, executor:)
15
+ @task_store = task_store
16
+ @executor = executor
17
+ end
18
+
19
+ def call(command)
20
+ task_id = command.payload[:task_id] || command.payload["task_id"]
21
+ raise Insika::ValidationError, "task_id is required" if task_id.to_s.empty?
22
+
23
+ task = @task_store.find(task_id)
24
+ raise Insika::NotFoundError, "task '#{task_id}' not found" unless task
25
+
26
+ @executor.cancel(task_id) # no-op if there is no live fiber in this process
27
+ # Does not transition status nor touch the persisted mailbox_state: it only uses
28
+ # the in-process mailbox (Async::Queue). Returns the current state after the post.
29
+ @task_store.find(task_id)
30
+ end
31
+ end
32
+ end
33
+ end