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,1680 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+ require "securerandom"
5
+ require "async/queue"
6
+
7
+ module Insika
8
+ # Coordinates execution. It does not build context, decide policy, or talk to
9
+ # the provider. This file does NOT require ruby_llm at load-time —
10
+ # the require is lazy inside the chat methods.
11
+ #
12
+ # Surrounds the stages: spawn, state lifecycle
13
+ # (always via TaskStore), mailbox drain at the boundaries, in-process
14
+ # registration of live fibers (running?), and the emitter with meta + seq.
15
+ class Executor
16
+ def initialize(context_builder:, policy_engine:, middleware:, hooks:,
17
+ tool_registry:, skill_catalog:, profiles:,
18
+ session_store:, task_store:, checkpoint_store:,
19
+ event_stream:, workflow_registry: nil, pending_action_store: nil,
20
+ capability_registry: nil, tool_catalog: nil, memory_store: nil,
21
+ tool_trace_store: nil, settings_store: nil, content_filter_factory: nil,
22
+ delegation_store: nil, channel_delivery: nil, llm: nil)
23
+ @context_builder = context_builder
24
+ @policy_engine = policy_engine
25
+ @middleware = middleware
26
+ @hooks = hooks
27
+ @tool_registry = tool_registry
28
+ @skill_catalog = skill_catalog
29
+ # Legacy Hash -> StaticProfileSource; a ProfileSource passes through.
30
+ @profiles = ProfileSource.coerce(profiles)
31
+ @session_store = session_store
32
+ @task_store = task_store
33
+ @checkpoint_store = checkpoint_store
34
+ @event_stream = event_stream
35
+ @workflow_registry = workflow_registry # stage 6 of trigger_workflow
36
+ @pending_action_store = pending_action_store # approval gate
37
+ @capability_registry = capability_registry # capability resolution (nil = off)
38
+ @tool_trace_store = tool_trace_store # tool-call trace for Studio debugging (nil = off)
39
+ # Guardrails output filter (RFC-0009 §3.2): ->(state) { OutputFilter | nil }.
40
+ # Injected by the Safety::Factory; nil = off (parity — the stream is untouched).
41
+ # The INPUT guardrail is a Middleware (in the stack, not here); this is the seam
42
+ # for the stream-side redaction the Executor owns.
43
+ @content_filter_factory = content_filter_factory
44
+ # RFC-0010 Fase 2: durable record of ASYNC delegations. nil = async
45
+ # delegation OFF (only the synchronous spawn_subagent works — parity). When
46
+ # present, run_subagent(async: true) dispatches + returns immediately and the
47
+ # child's result is delivered to the parent session as a NEW turn on completion.
48
+ @delegation_store = delegation_store
49
+ # RFC-0011 §6.5: outbound delivery for Shape B channels. nil = no channel
50
+ # delivers out of band (parity — every surface today answers on the request's
51
+ # own connection). When present, a turn that CAME IN through a channel writes
52
+ # its answer to the outbox at the terminal and the dispatcher POSTs it.
53
+ @channel_delivery = channel_delivery
54
+ # RFC-0017 A2: the chat FACTORY this executor asks — a RubyLLM::Context (an
55
+ # isolated config dup) when the graph owns its credentials, nil = the
56
+ # process-wide RubyLLM constant (the historic single-graph deployment).
57
+ # Duck-typed: Context#chat and RubyLLM.chat take the same keywords.
58
+ @llm = llm
59
+ # LLM config v2 (§10): resolves the model at turn start (Chat > Agent >
60
+ # platform default) + model_policy + fallback chain. settings_store nil =
61
+ # no platform layer (pre-v2 behavior: the agent's own model is used as-is).
62
+ @model_resolver = ModelResolver.new(settings_store: settings_store)
63
+ # RFC-0015 §4: the platform layer of the queue policy (nil = per-agent and
64
+ # defaults only, which is `followup` with no window — today's behavior).
65
+ @settings_store = settings_store
66
+ # RubyLLM glue (stages 5-7): chat assembly delegated to ChatBuilder. Its
67
+ # optional deps tool_catalog (Tool Search) and memory_store (cross-session
68
+ # memory) matter only to it — nil = parity (deferred
69
+ # not partitioned; no system remember).
70
+ @chat_builder = ChatBuilder.new(
71
+ tool_registry: tool_registry, skill_catalog: skill_catalog,
72
+ checkpoint_store: checkpoint_store, event_stream: event_stream, hooks: hooks,
73
+ tool_catalog: tool_catalog, memory_store: memory_store,
74
+ # RFC-0010: the ChatBuilder wires the spawn_subagent system tool (gated by
75
+ # profile.subagents) and hands it this Executor as the runner. `self` is not
76
+ # yet fully built here, but the ChatBuilder only STORES it (used per-turn).
77
+ subagent_runner: self
78
+ )
79
+ # Stage-3-tail tool assembly (capability resolution, instantiation, D2
80
+ # injection, dedup join, ToolEnvelope wrap) — extracted collaborator (§11 B5).
81
+ @tool_assembly = ToolAssembly.new(
82
+ tool_registry: tool_registry, capability_registry: capability_registry,
83
+ event_stream: event_stream, checkpoint_store: checkpoint_store,
84
+ tool_trace_store: tool_trace_store
85
+ )
86
+ @running = {} # task_id => TaskActor (live fibers in this process)
87
+ @seqs = Hash.new(0) # monotonic counter per task
88
+ @supervised = false # serving mode? — see #turn_parent
89
+ @supervisor = nil # lazy long-lived supervisor (created when serving)
90
+ @session_actors = {} # session_id => SessionActor (FIFO queue)
91
+ @draining = false # shutdown drain (RFC-0016 A3) — see #begin_drain!
92
+ end
93
+
94
+ # Turns on SERVING mode: the composition root's serving arm (serve.rb /
95
+ # config.ru) sets true AFTER recovery. Under HTTP `spawn` runs on the request's
96
+ # EPHEMERAL fiber; without this the turn would be its child and the runtime
97
+ # would CANCEL it on disconnect (violates the contract: "execution belongs to
98
+ # the runtime, not the connection"). When on, the turn is born a child of a
99
+ # long-lived supervisor (sibling of the accept loop) and outlives the
100
+ # connection. false (default) = parents on the current fiber: at recovery/boot
101
+ # and in tests the owner WANTS to wait for the turn to finish (structured
102
+ # concurrency).
103
+ attr_accessor :supervised
104
+
105
+ # RFC-0016 A3: closes the TURN intake for shutdown. Armed by Insika::Shutdown
106
+ # when the process is asked to stop: from here on a new top-level turn is left
107
+ # `:queued` (durable — the next boot's recovery replays it) instead of
108
+ # spawning, while the in-flight turns run to their natural end. One-way by
109
+ # design: a draining process never takes work again.
110
+ def begin_drain!
111
+ @draining = true
112
+ end
113
+
114
+ def draining? = @draining
115
+
116
+ # The turns still running in THIS process — what a drain waits on.
117
+ def in_flight = @running.keys
118
+
119
+ # In-process registry of live fibers (ResumeTask's criterion).
120
+ def running?(task_id) = @running.key?(task_id)
121
+
122
+ # CancelTask's access point: posts :cancel if there is a live fiber.
123
+ # Idempotent no-op if there is none (terminal/orphan). Returns whether there
124
+ # was a fiber.
125
+ def cancel(task_id)
126
+ actor = @running[task_id]
127
+ actor&.post(:cancel)
128
+ !actor.nil?
129
+ end
130
+
131
+ # PauseTask's access point: posts :pause if there is a live fiber; the turn
132
+ # suspends at the next boundary (drain_and_maybe_suspend). Idempotent no-op
133
+ # if there is none. Returns whether there was a fiber.
134
+ def pause(task_id)
135
+ actor = @running[task_id]
136
+ actor&.post(:pause)
137
+ !actor.nil?
138
+ end
139
+
140
+ # ResumeTask's access point for a paused IN-PROCESS task:
141
+ # posts :resume on the live fiber (which is blocked in await). Returns whether
142
+ # there was a live fiber — the handler decides between in-process resume and
143
+ # crash re-dispatch based on that.
144
+ def resume_live(task_id)
145
+ actor = @running[task_id]
146
+ actor&.post(:resume)
147
+ !actor.nil?
148
+ end
149
+
150
+ # ApproveAction's access point: WAKES the turn suspended in
151
+ # :waiting by posting :approval on the live fiber. The decision was already
152
+ # written to the store by the handler BEFORE this post (request_approval
153
+ # re-reads it from the store). No-op if there is no live fiber (process
154
+ # crashed) — recovery re-executes and uses the durable decision. Returns
155
+ # whether there was a fiber.
156
+ def approve(task_id)
157
+ actor = @running[task_id]
158
+ actor&.post(:approval)
159
+ !actor.nil?
160
+ end
161
+
162
+ # Approval gate, called by the ToolEnvelope at stage 6 when the
163
+ # tool requires approval. Creates/queries the PendingAction (deterministic id
164
+ # by task+turn+tool — per-tool correlation as with the side-effect),
165
+ # suspends the turn in :waiting and BLOCKS (await(:approval)) until the
166
+ # operator resolves it via ApproveAction. The AUTHORITATIVE decision comes
167
+ # from the durable store (crash-safe): on a post-crash re-execution, an
168
+ # already-resolved PendingAction is reused without re-suspending; a :pending
169
+ # one re-suspends.
170
+ # -> "approved" | "rejected".
171
+ def request_approval(task:, turn:, tool:, args:, actor:)
172
+ # Fail-closed: requiring approval with nowhere to persist/query the decision
173
+ # is a misconfiguration — fail LOUD, never hang nor auto-approve.
174
+ if @pending_action_store.nil?
175
+ raise Insika::Error, "tool '#{tool}' requires approval but PendingActionStore is not configured"
176
+ end
177
+
178
+ id = pending_id(task.id, turn, tool)
179
+ existing = @pending_action_store.find(id)
180
+ return existing.status.to_s if existing && existing.status != :pending # re-execution: already resolved
181
+
182
+ unless existing
183
+ @pending_action_store.create(id: id, task_id: task.id, turn: turn, tool: tool, args: args || {})
184
+ emit(:approval_requested, { pending_id: id, tool: tool.to_s, args: args }, task: task)
185
+ end
186
+
187
+ @task_store.transition(task.id, to: :waiting) if @task_store.find(task.id).status == :running
188
+
189
+ # Awaits the resolution of THIS pending. A spurious :approval (duplicate or
190
+ # from another pending of the same actor) that wakes up before resolution is
191
+ # ignored (re-await) — fail-closed: only the real resolution of this id
192
+ # unblocks.
193
+ status = nil
194
+ loop do
195
+ actor.await(reason: :approval) # blocks (or raises on :cancel/:timeout)
196
+ status = @pending_action_store.find(id)&.status
197
+ break unless status == :pending
198
+ end
199
+
200
+ @task_store.transition(task.id, to: :running)
201
+ (status || :rejected).to_s # fail-closed: missing record -> reject (defensive)
202
+ end
203
+
204
+ # Stage 1 (async part): creates the actor, registers it and fires the fiber.
205
+ # Called by the turn handlers (SendMessage/ResumeTask/TriggerWorkflow).
206
+ def spawn(task, profile:, resume_from: nil)
207
+ raise Insika::ValidationError, "task already running: #{task.id}" if running?(task.id)
208
+
209
+ actor = TaskActor.new(task_id: task.id, parent: turn_parent)
210
+ @running[task.id] = actor
211
+ actor.run { execute(task, profile: profile, resume_from: resume_from, actor: actor) }
212
+ task.id
213
+ end
214
+
215
+ # Turn entry point that RESPECTS the session: a turn with a
216
+ # session_id is SERIALIZED in that session's SessionActor queue (one at a
217
+ # time); without a session_id (one-shot/history) it goes straight to spawn
218
+ # (standalone).
219
+ def spawn_in_session(task, profile:, resume_from: nil)
220
+ # RFC-0016 A3: the intake is closed. The task is already durable (:queued);
221
+ # answering with its id and spawning NOTHING is what "stops accepting new
222
+ # turns" means — the next boot's recovery replays it. Subagent turns are NOT
223
+ # gated (they spawn directly): a child of an in-flight parent is part of the
224
+ # work the drain is waiting FOR, and refusing it would wedge the parent.
225
+ return defer_turn(task) if @draining
226
+
227
+ # SessionActor only in SERVING mode (@supervised): serializes concurrent
228
+ # REQUESTS. At boot/recovery (non-supervised) the replay is sequential and
229
+ # the long-lived loop would hang the Boot's Sync — use direct spawn (the
230
+ # owner awaits the turn). One-shot/history (no session_id)
231
+ # never serialize.
232
+ unless @supervised && task.session_id
233
+ return spawn(task, profile: profile, resume_from: resume_from)
234
+ end
235
+
236
+ session_actor(task.session_id).enqueue(task, profile: profile, resume_from: resume_from,
237
+ policy: queue_policy(profile, task.session_id))
238
+ end
239
+
240
+ # RFC-0015 §5.3 — the `collect` door, asked BEFORE a task is created.
241
+ # -> the task id the fragment joined, or nil (create a task and spawn as usual).
242
+ #
243
+ # Asking first is what keeps the store clean: creating a task and then
244
+ # discarding it would leave an orphan :queued record for every fragment, and
245
+ # `queued` is what Recovery replays at boot.
246
+ def collect_into_pending(session_id, text, profile:)
247
+ return nil unless @supervised && session_id
248
+
249
+ policy = queue_policy(profile, session_id)
250
+ return nil unless policy.collect? && policy.debounce?
251
+
252
+ actor = @session_actors[session_id]
253
+ return nil unless actor&.alive?
254
+
255
+ actor.collect(text)
256
+ end
257
+
258
+ # RFC-0015 §5.1 — the `steer` door: a message for a session whose turn is ALREADY
259
+ # running is appended to that run instead of becoming a turn of its own.
260
+ # -> the RUNNING task's id (the turn that will answer it), or nil (create a task and
261
+ # spawn as usual, which is `followup`).
262
+ #
263
+ # Asked BEFORE a task is created, like the `collect` door, and for the same reason.
264
+ # The post lands in the turn's mailbox; `SteerInjector` reads it at the next
265
+ # tool-batch boundary. Nothing here touches the run in flight — a message that no
266
+ # boundary ever arrives for is released as a follow-up turn (#release_steered).
267
+ def steer_into_running(session_id, text, profile:)
268
+ return nil unless @supervised && session_id
269
+
270
+ policy = queue_policy(profile, session_id)
271
+ return nil unless policy.steer?
272
+
273
+ session_actor = @session_actors[session_id]
274
+ return nil unless session_actor&.alive?
275
+
276
+ # No turn running (or one still at the door): there is nothing to steer INTO.
277
+ # A turn at the door belongs to `collect`, which is a different mode.
278
+ task = session_actor.current_task
279
+ return nil if task.nil?
280
+ # A workflow turn orchestrates RubyLLM itself and has no Insika chat to append to
281
+ # (docs/WORKFLOWS.md says so). Refused at the door so the message becomes an
282
+ # ordinary next turn instead of a phantom one.
283
+ return nil if workflow_turn?(task)
284
+
285
+ actor = @running[task.id]
286
+ return nil if actor.nil?
287
+ # The bound is on what ONE run may absorb, so it counts posts and not the buffer:
288
+ # a message already injected still spent its slot. Overflow degrades to
289
+ # `followup` rather than growing an unbounded tail.
290
+ return nil if actor.user_messages_posted >= policy.steer_max_messages
291
+
292
+ actor.post(:user_message, text)
293
+ task.id
294
+ end
295
+
296
+ # RFC-0015 §6.4 — the `interrupt` door: the turn in flight is answering a question
297
+ # the customer has already replaced, so it is abandoned and the new message becomes an
298
+ # ordinary turn. -> the abandoned task's id, or nil (nothing was running).
299
+ #
300
+ # Unlike `collect`/`steer` this one JOINS nothing: `replaced_by` already has its own
301
+ # task and its own reply, so there is no verdict to report and every surface can use
302
+ # it, `/v1/responses` included.
303
+ #
304
+ # What "abandon" means here is Insika's existing cancellation semantics, unchanged:
305
+ # `:cancel` is observed only at a stage boundary, so a tool call in flight runs to
306
+ # completion and is recorded. Cancelling the not-yet-started calls of a batch would
307
+ # leave it half applied, and fabricating failure results would teach the model that
308
+ # tools failed when they did not (D7 records the same boundary for `turn_timeout`).
309
+ def interrupt_running(session_id, profile:, replaced_by: nil)
310
+ return nil unless @supervised && session_id
311
+
312
+ return nil unless queue_policy(profile, session_id).interrupt?
313
+
314
+ session_actor = @session_actors[session_id]
315
+ return nil unless session_actor&.alive?
316
+
317
+ task = session_actor.current_task
318
+ return nil if task.nil?
319
+
320
+ actor = @running[task.id]
321
+ return nil if actor.nil?
322
+
323
+ actor.post(:cancel)
324
+ emit(:turn_interrupted, { task_id: task.id, replaced_by: replaced_by }, task: task)
325
+ task.id
326
+ end
327
+
328
+ # The SessionActor writes the merged fragment through this (it has no store of
329
+ # its own, by design — it owns scheduling, not persistence).
330
+ attr_reader :task_store
331
+
332
+ # RFC-0015 §8. Emitted by the SessionActor when a window closes having merged
333
+ # more than one fragment. `arrivals` are the ISO8601 times each fragment landed
334
+ # — the ONLY record that they were separate messages, since a merged fragment
335
+ # creates no task of its own. Ids and times, never content.
336
+ def emit_coalesced(task, merged:, arrivals: [])
337
+ emit(:turn_coalesced, { task_id: task.id, merged: merged, arrivals: arrivals }, task: task)
338
+ end
339
+
340
+ # RFC-0015 §5.2 — a steered message the run could NOT absorb: no tool batch ever
341
+ # closed (a text-only turn), the batch ended in `halt_when`, the turn failed, or it
342
+ # was cancelled. The message is a person's and must not evaporate, so it is released
343
+ # as the next turn on this session — which is `followup`, arrived at late.
344
+ #
345
+ # Runs in `execute`'s ensure, on the dying turn's fiber: `spawn_in_session` only
346
+ # enqueues, and the session loop is still awaiting THIS turn, so the follow-up runs
347
+ # after it, in order.
348
+ def release_steered(task, profile, actor)
349
+ # Cheap gate first: a turn nobody steered pays one integer read and no store round
350
+ # trip, which is every turn on every agent that never turned the mode on.
351
+ return unless actor.user_messages_posted.positive?
352
+
353
+ # Only a turn that actually FINISHED releases. A process going down (Async::Stop
354
+ # through this ensure) leaves the task `:running` for Recovery to replay, and
355
+ # spawning a follow-up during shutdown would parent a turn on a supervisor that is
356
+ # already stopping. The honest limitation: a steered message lives in memory until a
357
+ # boundary writes it to the transcript, so a hard stop in that window loses it.
358
+ current = @task_store.find(task.id)
359
+ return unless current && TERMINAL_STATUSES.include?(current.status)
360
+
361
+ texts = actor.take_user_messages!
362
+ return if texts.empty?
363
+
364
+ command = Insika::Command.build(
365
+ :send_message,
366
+ # No `origin`: a person typed this, which is exactly what an absent origin means.
367
+ { "agent" => profile.id, "message" => texts.join("\n"), "session_id" => task.session_id }
368
+ ).to_h
369
+ follow_up = @task_store.create(command: command, session_id: task.session_id)
370
+ emit(:turn_steer_released, { task_id: task.id, released_as: follow_up.id, count: texts.size },
371
+ task: task)
372
+ spawn_in_session(follow_up, profile: profile)
373
+ rescue Insika::Error
374
+ # Best-effort: the turn is already terminal and durable, and a store that refuses
375
+ # here must not turn a committed turn into a failed one. The message is then lost,
376
+ # and the ABSENCE of :turn_steer_released is what says so — there is no half state.
377
+ nil
378
+ end
379
+
380
+ # Runs ONE turn serially (called by the SessionActor loop):
381
+ # spawns (the turn is born a child of the supervisor, non-blocking) and AWAITS
382
+ # its completion before returning — that is what serializes the session. A
383
+ # turn error is already mapped to a terminal state inside its own fiber (single
384
+ # capture); here we only ensure the session loop does not die.
385
+ def run_serial(task, profile:, resume_from: nil)
386
+ # RFC-0016 A3: a drain that started with turns already queued behind this
387
+ # session's current one must not keep feeding the loop — without this gate
388
+ # the drain would only converge when the whole backlog ran out.
389
+ return defer_turn(task) if @draining
390
+
391
+ spawn(task, profile: profile, resume_from: resume_from)
392
+ @running[task.id]&.wait
393
+ rescue Async::Stop
394
+ raise # shutdown: propagate (ends the session loop)
395
+ rescue StandardError => e
396
+ # A SYNCHRONOUS spawn error (before the fiber): execute's single capture
397
+ # does not act (the turn never ran). Mark :failed here so as NOT to orphan
398
+ # the task as :queued with no terminal state nor event (the client would
399
+ # hang).
400
+ fail_spawn(task, e)
401
+ end
402
+
403
+ # Shuts down all SessionActors (server shutdown / tests — the loop blocks
404
+ # forever on dequeue when idle).
405
+ def stop_session_actors
406
+ @session_actors.each_value(&:stop)
407
+ @session_actors.clear
408
+ nil
409
+ end
410
+
411
+ # RFC-0010 (item 21): runs a CHILD agent turn (called by Tools::Subagent during
412
+ # stage 6). Isolated context (fresh child session), capability NON-inheritance
413
+ # (child profile resolved fresh), environment inheritance (model/thinking seeded
414
+ # from the parent). NEVER raises: a bad agent/depth/child failure is a message
415
+ # to the model, not a turn-killer.
416
+ #
417
+ # async:false (default, Fase 1) — SYNCHRONOUS: runs the child inside the parent's
418
+ # fiber and returns { text:, session_id: } (the child result is the tool result).
419
+ # async:true (Fase 2) — DURABLE dispatch: spawns the child NON-blocking, persists
420
+ # a Delegation, returns { dispatched:, agent:, session_id: } immediately; the
421
+ # parent turn ends and the child's result is later delivered as a NEW turn on
422
+ # the parent session (needs a delegation_store — else falls back to sync).
423
+ def run_subagent(agent:, message:, parent_state:, async: false)
424
+ plan = plan_subagent({ "agent" => agent, "message" => message }, parent_state)
425
+ return { error: plan[:error] } if plan[:error]
426
+
427
+ if async && @delegation_store
428
+ dispatch_async_child(plan[:profile], plan[:message], plan[:depth], parent_state)
429
+ else
430
+ spawn_and_await_child(plan[:profile], plan[:message], plan[:depth], parent_state)
431
+ end
432
+ end
433
+
434
+ # RFC-0010 §A (fan-out): runs SEVERAL child turns IN PARALLEL and returns all
435
+ # results together, in the requested order. This is the real latency win — the
436
+ # children overlap their provider waits on the reactor, so wall-clock ≈ the
437
+ # slowest child, not the sum. Always sync-join (a combined result in the parent's
438
+ # turn); the async deliver-as-new-turn mode is single-child only, by design.
439
+ # NEVER raises: per-task errors keep their slot; a bad envelope returns { error: }.
440
+ # -> { results: [{agent:, text:, session_id:} | {agent:, error:}, ...] } | { error: }
441
+ def run_subagents(tasks:, parent_state:)
442
+ list = Array(tasks)
443
+ return { error: "tasks must be a non-empty list of {agent, message}" } if list.empty?
444
+
445
+ cap = SubagentGraph.fan_out_cap
446
+ return { error: "too many subagents in one call: #{list.size} (max #{cap})" } if list.size > cap
447
+
448
+ plans = list.map { |t| plan_subagent(t, parent_state) }
449
+ { results: spawn_all_and_project(plans, parent_state) }
450
+ end
451
+
452
+ # RFC-0010 Fase 2 (boot): reconciles ASYNC delegations after a crash so a
453
+ # completed child's result is never lost. For each undelivered Delegation:
454
+ # · child TERMINAL, not captured -> capture + deliver.
455
+ # · child TERMINAL, captured (completed) -> deliver (crash before delivery).
456
+ # · child NOT terminal -> left as-is; the normal task Recovery resumes the
457
+ # child and its terminal hook (finalize_delegation) delivers when it finishes.
458
+ # Called once at boot AFTER the task Recovery. No-op without a delegation_store.
459
+ # -> { delivered: [ids] }
460
+ def recover_delegations
461
+ return { delivered: [] } unless @delegation_store
462
+
463
+ delivered = []
464
+ @delegation_store.undelivered.each do |deleg|
465
+ child = @task_store.find(deleg.child_task_id)
466
+ next unless child && TERMINAL_STATUSES.include?(child.status)
467
+
468
+ finalize_delegation(child) # capture (if needed) + claim + deliver
469
+ delivered << deleg.id
470
+ end
471
+ { delivered: delivered }
472
+ end
473
+
474
+ # RFC-0011 §6.5 (boot): re-drives the outbound replies a previous process
475
+ # recorded and never claimed. Records left `delivering` are NOT swept — that
476
+ # process may have POSTed before it died, and re-sending is the duplicate the
477
+ # claim exists to prevent. No-op without a channel_delivery.
478
+ # -> { dispatched: [ids] }
479
+ def recover_channel_deliveries
480
+ return { dispatched: [] } unless @channel_delivery
481
+
482
+ @channel_delivery.sweep
483
+ end
484
+
485
+ # Stages 2..9. Runs INSIDE the task's fiber.
486
+ def execute(task, profile:, actor:, resume_from: nil)
487
+ # Resume of a crash orphan: the interrupted attempt's Execution was left OPEN
488
+ # (the fiber died). The TaskStore forbids opening a second one while one is
489
+ # open -> close the orphan as :interrupted before opening the N+1 (a new
490
+ # entry, never overwrites).
491
+ close_orphan_execution(task) if resume_from
492
+ @task_store.begin_execution(task.id) # attempt N+1
493
+ # queued (normal spawn) and paused/waiting (resume) -> running. An orphan is
494
+ # already :running (running->running is invalid) -> no transition.
495
+ status = @task_store.find(task.id).status
496
+ @task_store.transition(task.id, to: :running) if %i[queued paused waiting].include?(status)
497
+ emit(:task_started, started_data(task, profile), task: task)
498
+
499
+ actor.drain!
500
+ run_pipeline(task, profile, actor, resume_from)
501
+ # SINGLE capture at the top of the fiber: a single place maps
502
+ # error -> terminal state -> events. Stages do no rescue of their own
503
+ # (except tool, RubyLLM semantics). The fiber NEVER re-raises.
504
+ rescue CancelledError
505
+ # cancel is not an error: transition WITHOUT error: (does not close the
506
+ # Execution), then finish_execution closes it with outcome :cancelled.
507
+ @task_store.transition(task.id, to: :cancelled)
508
+ @task_store.finish_execution(task.id, outcome: :cancelled)
509
+ emit(:task_cancelled, { task_id: task.id }, task: task)
510
+ rescue PolicyDenied => e
511
+ emit(:policy_denied, { policy: e.policy, reason: e.reason }, task: task)
512
+ fail_task(task, e, stage: :policy)
513
+ rescue Insika::WorkflowSchemaError => e
514
+ # Item 22 / §4.4: a workflow OUTPUT that violates its output_schema. Distinct
515
+ # stage so a contract breach is not conflated with an :unknown failure. (INPUT
516
+ # is validated synchronously in TriggerWorkflow -> 422, never reaches here.)
517
+ fail_task(task, e, stage: :workflow_schema)
518
+ rescue ContextError => e
519
+ fail_task(task, e, stage: :context)
520
+ rescue CapabilityError => e
521
+ fail_task(task, e, stage: :capability)
522
+ rescue ProviderError => e
523
+ fail_task(task, e, stage: :ruby_llm)
524
+ rescue StoreError => e
525
+ fail_task(task, e, stage: :persistence)
526
+ rescue TimeoutError => e
527
+ fail_task(task, e, stage: e.stage)
528
+ rescue StandardError => e
529
+ fail_task(task, e, stage: :unknown)
530
+ ensure
531
+ @running.delete(task.id) # ALWAYS deregister (a false-positive running? would break the resume)
532
+ # Deregistered FIRST on purpose: from here on the `steer` door finds no actor for
533
+ # this session and answers nil, so a message arriving during the release becomes
534
+ # its own turn instead of a post into a mailbox nobody reads again.
535
+ release_steered(task, profile, actor)
536
+ end
537
+
538
+ private
539
+
540
+ # RFC-0015 §4 — resolves session vars > profile.limits > settings["queue"] >
541
+ # defaults. One session read plus one settings read per message, the same
542
+ # order of cost the EdgeLimiter already pays per turn. A missing session (or
543
+ # no session store) simply drops the vars layer.
544
+ def queue_policy(profile, session_id)
545
+ vars = session_id && @session_store&.find(session_id)&.vars
546
+ QueuePolicy.resolve(profile, settings_store: @settings_store, vars: vars)
547
+ end
548
+
549
+ # Lazy SessionActor per session, parented in the turn scope:
550
+ # the session loop outlives the connection, like the supervisor. Revalidates
551
+ # liveness: if the cached loop died (supervisor recreated/stopped), create a
552
+ # new one — otherwise the queued turns would be black-holed in a dead loop.
553
+ def session_actor(session_id)
554
+ existing = @session_actors[session_id]
555
+ return existing if existing&.alive?
556
+
557
+ @session_actors[session_id] =
558
+ SessionActor.new(session_id: session_id, executor: self, parent: turn_parent)
559
+ end
560
+
561
+ # RFC-0016 A3 — a turn that arrived while the process is draining: left
562
+ # `:queued` on purpose (recovery replays :queued at the next boot). The event
563
+ # is the deferral's only trace — without it, "why was my message answered
564
+ # only after the deploy" is unanswerable.
565
+ def defer_turn(task)
566
+ emit(:turn_deferred, { task_id: task.id }, task: task)
567
+ task.id
568
+ end
569
+
570
+ # Marks :failed a task whose turn FAILED at spawn (before the fiber).
571
+ # Idempotent against a terminal state; StoreError re-raises (the session loop
572
+ # handles it).
573
+ def fail_spawn(task, error)
574
+ current = @task_store.find(task.id)
575
+ return if current.nil? || TERMINAL_STATUSES.include?(current.status)
576
+
577
+ @task_store.transition(task.id, to: :failed,
578
+ error: { class: error.class.name, message: error.message, stage: :spawn })
579
+ emit(:task_failed, { task_id: task.id, error: error.class.name, message: error.message }, task: task)
580
+ rescue Insika::Error
581
+ nil
582
+ end
583
+
584
+ # Parent of the turn's fiber. Non-serving: the current fiber (the owner waits
585
+ # for the turn). Serving: a long-lived supervisor created lazily at the reactor
586
+ # BOUNDARY — the task whose parent is the reactor itself (sibling of the accept
587
+ # loop), outside the subtree of any request. This way the turn outlives the
588
+ # request stop (disconnect). One supervisor per Executor, reused while alive.
589
+ def turn_parent
590
+ return Async::Task.current unless @supervised
591
+ return @supervisor if @supervisor&.running?
592
+
593
+ reactor = Async::Task.current.reactor
594
+ node = Async::Task.current
595
+ node = node.parent while node.parent && node.parent != reactor
596
+ # Idle with no spin nor deprecated API (Async::Task#sleep is deprecated in
597
+ # 2.42): blocks on a dequeue that never arrives. Ends only when the scope is
598
+ # stopped (server shutdown) — then any child turns still running go with it.
599
+ # In a deployment that is the LAST resort, not the plan: Insika::Shutdown
600
+ # drains first (RFC-0016 A3), so only what outlives the drain deadline dies
601
+ # here, `:running`, for the next boot's recovery to replay.
602
+ @supervisor = node.async { |t| t.annotate("harness-turn-supervisor"); Async::Queue.new.dequeue }
603
+ end
604
+
605
+ # Deterministic PendingAction id: correlation by task+turn+tool.
606
+ # Limitation inherited from the side-effect: the SAME tool with approval more
607
+ # than once in a turn collides (the 2nd reuses the 1st's decision) — per-step
608
+ # checkpointing is a future slice. One call per tool is safe.
609
+ def pending_id(task_id, turn, tool) = "#{task_id}:#{turn}:#{tool}"
610
+
611
+ # §11 B2: all readings of the persisted command go through rebuild_command
612
+ # (the single normalizer). command_type stays a STRING (the :task_started
613
+ # event and the Telemetry attribute are string-typed).
614
+ def command_type(task)
615
+ rebuild_command(task).type.to_s
616
+ end
617
+
618
+ # Closes the orphan Execution (open) of an attempt interrupted by a crash,
619
+ # marking it :interrupted — the record of what happened is preserved; the
620
+ # N+1 attempt is opened right after by begin_execution.
621
+ def close_orphan_execution(task)
622
+ open = @task_store.find(task.id).executions.last
623
+ @task_store.finish_execution(task.id, outcome: :interrupted) if open && open.finished_at.nil?
624
+ end
625
+
626
+ # Maps error -> task :failed + events. `transition` with error: ALREADY closes
627
+ # the open Execution (real TaskStore) — do NOT call finish_execution
628
+ # (double-close). The previous checkpoint is NEVER touched on failure. Never
629
+ # re-raises: the fiber dies clean.
630
+ def fail_task(task, error, stage:)
631
+ # Defense-in-depth: if the task is already terminal (e.g. a failure in
632
+ # cleanup AFTER transition(:completed)), completed->failed is invalid and
633
+ # would raise ArgumentError INSIDE the rescue, leaking from the fiber. In
634
+ # that case only report the error — the durability of the committed turn is
635
+ # preserved. This :error is the ONE deliberate, non-twin executor error
636
+ # signal (R2b): the terminal already fired, so a session-scoped subscriber
637
+ # is the only one that may still see it. Same family as the overflow :error.
638
+ current = @task_store.find(task.id)
639
+ if current && TERMINAL_STATUSES.include?(current.status)
640
+ emit(:error, { message: error.message }, task: task)
641
+ return nil
642
+ end
643
+
644
+ @task_store.transition(task.id, to: :failed,
645
+ error: { class: error.class.name, message: error.message, stage: stage })
646
+ emit(:task_failed, { task_id: task.id, error: error.class.name, message: error.message }, task: task)
647
+ # RFC-0010 Fase 2: a FAILED delegation child still delivers — the parent
648
+ # receives an error note as a new turn (never left hanging).
649
+ finalize_delegation(task)
650
+ nil
651
+ end
652
+
653
+ TERMINAL_STATUSES = %i[completed failed cancelled].freeze
654
+ private_constant :TERMINAL_STATUSES
655
+
656
+ # Stages 2-9, with mailbox drain only at the boundaries and the
657
+ # turn-timeout wrapping everything via Async::Task#with_timeout — NEVER
658
+ # stdlib Timeout.timeout.
659
+ def run_pipeline(task, profile, actor, resume_from)
660
+ timing = TurnTiming.new if TurnTiming.enabled?
661
+ timing&.mark(:prep_start)
662
+ state = build_turn_state(task, profile, resume_from)
663
+ turn_timeout = turn_timeout_for(profile)
664
+
665
+ Async::Task.current.with_timeout(turn_timeout) do
666
+ # :task pair: wraps the turn's stages. before_task may
667
+ # rewrite the TurnState before stage 2; after_task runs after stage 9.
668
+ # The block-param `state` shadows the outer one (uses the TurnState
669
+ # possibly rewritten by before_task). Subject == result == TurnState
670
+ # (the Response content lives in the :done event).
671
+ @hooks.around(:task, state) do |state|
672
+ prepare_turn(task, profile, state, actor, resume_from) # stages 2-3 (mutates state)
673
+
674
+ # stage 4: Middleware wraps stages 5-9. A link that
675
+ # short-circuits does NOT call the terminal and sets state.halt_reason.
676
+ terminal_ran = false
677
+ @middleware.call(state) do |st|
678
+ raise Insika::Error, "turn halted: #{st.halt_reason}" if st.halt_reason
679
+
680
+ terminal_ran = true
681
+ run_turn_body(task, profile, st, actor, timing) # stages 5-9
682
+ end
683
+
684
+ # A Middleware short-circuited (did not call the terminal). Three cases:
685
+ # · halt_response set -> GRACEFUL halt (RFC-0009 §3.1): the turn COMPLETES
686
+ # with a safe reply, reusing stages 8-9, without ever touching the LLM.
687
+ # · halt_reason set -> halt-as-FAILURE (the pre-existing contract).
688
+ # · neither -> contract violation (short-circuit with no signal).
689
+ if !terminal_ran && state.halt_response
690
+ complete_with_halt(task, profile, state)
691
+ elsif state.halt_reason
692
+ raise Insika::Error, "turn halted: #{state.halt_reason}"
693
+ elsif !terminal_ran
694
+ raise Insika::Error, "middleware short-circuited without halt_reason"
695
+ end
696
+
697
+ state # subject of the :task pair (after_task receives it; the caller discards)
698
+ end.tap { |st| emit_guardrail_flags(task, st) }
699
+ end
700
+ rescue Async::TimeoutError
701
+ raise Insika::TimeoutError.new("turn exceeded #{turn_timeout}s", stage: :turn)
702
+ end
703
+
704
+ # Builds the turn's mutable state (turn number, message, memory tenant, D2
705
+ # turn context). before_task (hooks.around) may still rewrite it before stage 2.
706
+ def build_turn_state(task, profile, resume_from)
707
+ turn = resume_from ? resume_from.turn : 1
708
+ state = TurnState.new(task: task, profile: profile, turn: turn,
709
+ message: extract_message(task))
710
+ state.tenant = memory_tenant(task) # WRITE-path memory scope (`remember`); =chat (D3)
711
+ state.turn_context = build_turn_context(task, profile, state) # data-tools' ctx.* (D2/G4)
712
+ state.resumed = !resume_from.nil? # EdgeLimiter: an admitted turn is never re-counted
713
+ # RFC-0015: resolved for the RUN, not per message, so what the turn accepts cannot
714
+ # change under it. Same cost as the EdgeLimiter's per-turn resolution. Only for a
715
+ # SESSION turn: steering needs a session to arrive through, and resolving here for a
716
+ # one-shot would make an unrelated turn fail on a queue key it can never use.
717
+ state.queue_policy = task.session_id ? queue_policy(profile, task.session_id) : nil
718
+ state
719
+ end
720
+
721
+ # with_timeout budget for the turn. A turn that MAY require human approval
722
+ # gets approval_timeout (~1h) so the wrapper does not kill a legitimate
723
+ # operator wait. LLM runaway is already bounded by max_tool_calls + turn_timeout.
724
+ def turn_timeout_for(profile)
725
+ base = profile.limits[:turn_timeout] || 300
726
+ return base if Array(profile.approvals_required).empty?
727
+
728
+ [base, profile.limits[:approval_timeout] || 3_600].max
729
+ end
730
+
731
+ # Stages 2-3: Context -> initial checkpoint -> capability resolution -> Policy
732
+ # -> tool assembly, each followed by a mailbox drain at the boundary. Mutates
733
+ # `state` in place (the TurnState possibly rewritten by before_task).
734
+ def prepare_turn(task, profile, state, actor, resume_from)
735
+ # stage 2: Context. The :prompt hook pair is wrapped INSIDE the
736
+ # ContextBuilder#call — do NOT wrap here (a double-wrap would fire the hooks
737
+ # twice). Hooks is the SAME instance injected into the Builder and here.
738
+ request = build_context_request(task, profile, state, resume_from)
739
+ state.context = @context_builder.call(request)
740
+ drain_and_maybe_suspend(task, actor)
741
+
742
+ # INITIAL checkpoint of the turn ("the checkpoint of turn n contains the
743
+ # state AT THE START of turn n"). Without it, a crash mid stage 6 (before
744
+ # stage 8) would orphan the task WITH NO checkpoint -> unrecoverable.
745
+ # Idempotent: only writes on the 1st turn of a new task.
746
+ save_initial_checkpoint(task, profile, state)
747
+
748
+ # capability-resolution sub-step BETWEEN Context and Policy: fills
749
+ # state.capability_names for the POST-Policy join; candidate_tools stays
750
+ # tool_registry.entries (a capability does not go through the ToolAllowlist).
751
+ state.capability_names = resolve_capabilities(profile, state.context)
752
+
753
+ # stage 3: Policy (candidate_skills from the CATALOG; candidate_tools =
754
+ # tool_registry.entries, direct tools only).
755
+ resolution = @policy_engine.decide(policy_request(profile, task, state))
756
+ # on resume, tool calls already completed in the interrupted turn are
757
+ # "skipped" (standalone key ∪ turn checkpoint), propagated to promoted tools too.
758
+ skip = resume_from ? @checkpoint_store.side_effects(task.id, turn: state.turn) : []
759
+ state.skip_side_effects = skip
760
+ # wire the approval gate into the state (the ToolEnvelope reads it at stage 6).
761
+ state.actor = actor
762
+ state.approval_coordinator = self
763
+ state.requires_approval = resolution.requires_approval
764
+ state.allowed_tools = wrap_tools(assemble_tool_instances(resolution.allowed_tools, state), state, skip)
765
+ state.allowed_skills = resolution.allowed_skills
766
+ drain_and_maybe_suspend(task, actor)
767
+ end
768
+
769
+ # Stages 5-9 (inside the Middleware wrap): assemble chat, the single agent
770
+ # interaction, persistence, terminal event. `st` is the Middleware-yielded state.
771
+ def run_turn_body(task, profile, st, actor, timing = nil)
772
+ # stage 5: assemble chat + check mailbox (send_message only; a workflow does
773
+ # not use the Insika chat — it orchestrates RubyLLM internally).
774
+ drain_and_maybe_suspend(task, actor)
775
+ unless workflow_turn?(task)
776
+ st.chat = create_chat(profile, st)
777
+ @chat_builder.assemble(st.chat, st, emit: ->(type, data) { emit(type, data, task: task) })
778
+ # §11 R1: baseline = seeded-history size, before `ask` appends the turn.
779
+ st.chat_baseline = Array(st.chat.messages).size if st.chat.respond_to?(:messages)
780
+ end
781
+
782
+ # guardrails (RFC-0009 §3.2): per-turn stream redactor (nil = off).
783
+ st.output_filter = @content_filter_factory&.call(st)
784
+
785
+ # stage 6: the turn's single agent interaction (send_message -> chat.ask;
786
+ # trigger_workflow -> workflow.call). Returns the turn's final content.
787
+ content = run_agent_stage(task, st, timing)
788
+ st.response_content = content # after_task OutputValidator inspects this
789
+
790
+ # stage 8: Persistence (fixed order checkpoint->session->task). pure drain!
791
+ # (NEVER suspends at stage 8 — forbidden window): a :pause here arms the flag
792
+ # but is not honored (last stage); :cancel here still raises.
793
+ actor.drain!
794
+ persist_turn(task, profile, st, content)
795
+
796
+ # stage 9: Response. usage (tokens) captured at stage 6 travels in the
797
+ # terminal event -> /v1/responses usage + Telemetry (OTEL).
798
+ timing&.mark(:done)
799
+ data = { task_id: task.id, content: content, usage: st.usage }
800
+ data[:timing] = timing.to_h if timing # opt-in TTFB breakdown (INSIKA_TURN_TIMING)
801
+ emit(:task_completed, data, task: task)
802
+ end
803
+
804
+ def workflow_turn?(task)
805
+ command_type(task).to_s == "trigger_workflow"
806
+ end
807
+
808
+ # Stage 6: the single agent interaction. Returns the turn's final content.
809
+ def run_agent_stage(task, state, timing = nil)
810
+ if workflow_turn?(task)
811
+ # workflow = a Ruby callable that orchestrates RubyLLM internally (RubyLLM
812
+ # First). tools: are the SAME instances filtered by the Resolution and
813
+ # enveloped (stage 7) — the workflow inherits timeout/side-effect/skip.
814
+ # Item 22 / §4.4: the EXPOSED surface — the run (== task.id) is announced on
815
+ # the stream (:workflow_started), the RETURN is validated against the
816
+ # output_schema (WorkflowSchemaError -> :workflow_schema stage), and the
817
+ # typed output is published (:workflow_completed).
818
+ definition = @workflow_registry.definition(workflow_name(task))
819
+ emit(:workflow_started,
820
+ { run_id: task.id, workflow: definition.name, input: state.message || {} }, task: task)
821
+ output = @hooks.around(:agent, state) do |s|
822
+ # input omitted from the payload -> {} (the workflow expects a Hash).
823
+ definition.call(s.message || {}, context: s.context, tools: s.allowed_tools)
824
+ end
825
+ definition.validate_output!(output)
826
+ emit(:workflow_completed, { run_id: task.id, workflow: definition.name, output: output }, task: task)
827
+ output
828
+ else
829
+ filter = state.output_filter # RFC-0009 §3.2: nil = off (stream untouched)
830
+ timing&.mark(:ask)
831
+ # TurnOutput owns what the customer is allowed to read: chunks ride
832
+ # :intermediate live and only the message that ENDS the turn is published as
833
+ # :content. Registered on the chat (fresh per turn, so no callback leaks).
834
+ output = TurnOutput.new(filter: filter, emit: ->(type, data) { emit(type, data, task: task) },
835
+ public_intermediate: state.profile.stream_public?(:intermediate))
836
+ state.chat.after_message { |message| output.message_ended(message) } if state.chat.respond_to?(:after_message)
837
+ # RFC-0015 §5.2: `steer` only. Registered AFTER TurnOutput so the publishing
838
+ # decision for a message is made before anything is appended after it — the
839
+ # gem's callbacks are additive and run in registration order.
840
+ install_steer_injector(task, state)
841
+
842
+ # `asked` is what the provider returned, BEFORE the :agent after-hook had a
843
+ # chance to replace it — the only way to tell an explicit substitution from
844
+ # the ordinary "the hook returned what it received".
845
+ asked = nil
846
+ response = @hooks.around(:agent, state) do |s|
847
+ public_thinking = state.profile.stream_public?(:thinking)
848
+ asked = s.chat.ask(s.message) do |chunk|
849
+ emit_thinking(chunk, task, public: public_thinking)
850
+ next unless chunk.content
851
+
852
+ timing&.mark(:first_token) # first-write-wins -> the PROVIDER's TTFB
853
+ output.push(chunk.content)
854
+ end
855
+ end
856
+ # release the redactor's retained tail (a value that never completed into a
857
+ # match is emitted redacted-if-needed, not lost) before reading anything back.
858
+ output.flush
859
+ state.usage = with_model_source(usage_of(response), state.model_selection) unless halted?(response)
860
+
861
+ # BOUNDARY BEFORE THE ANSWER GOES OUT. A cancel that arrived while the provider
862
+ # was working used to be observed at stage 8 — AFTER `:content` had already been
863
+ # published — so the customer read the answer of a turn that then terminated
864
+ # `:cancelled` and persisted nothing: text delivered, transcript silent about it.
865
+ # Honoring it here is what makes `interrupt` (RFC-0015 §6.4) mean anything, and it
866
+ # is a safe boundary: the tool batch is finished and nothing is half applied.
867
+ # A `:pause` is deliberately NOT honored here (drain!, not the suspending form):
868
+ # holding a completed answer for an operator would strand it unpublished.
869
+ state.actor&.drain!
870
+
871
+ output.publish(turn_answer(response, asked, output, filter))
872
+ end
873
+ end
874
+
875
+ # RFC-0015 §5.2 — wires the tool-batch boundary that lets a message which arrived
876
+ # mid-run enter the conversation. No-op unless the agent asked for `steer`: an
877
+ # unregistered callback is the difference between a feature that is off and one that
878
+ # is on and finds nothing.
879
+ def install_steer_injector(task, state)
880
+ policy = state.queue_policy
881
+ return unless policy&.steer? && task.session_id && state.actor
882
+ # A chat that does not answer the three callbacks cannot host the boundary (the smoke
883
+ # shim, a minimal double). Steering is then simply off, never half-wired.
884
+ return unless %i[after_message after_tool_result add_message].all? { |m| state.chat.respond_to?(m) }
885
+
886
+ injector = SteerInjector.new(
887
+ chat: state.chat, actor: state.actor, policy: policy,
888
+ # `task_id` in the payload as well as the meta, so `:turn_steered` reads like
889
+ # `:turn_coalesced` for a subscriber that only looks at data.
890
+ emit: ->(type, data) { emit(type, data.merge(task_id: task.id), task: task) }
891
+ )
892
+ state.chat.after_message { |message| injector.message_ended(message) }
893
+ state.chat.after_tool_result { |result| injector.tool_result(result) }
894
+ injector
895
+ end
896
+
897
+ # WHAT THE CUSTOMER GETS, in precedence order. Published once, at the end of the
898
+ # stage, because the `:agent` after-hook runs after the message boundary and is
899
+ # allowed to have the last word.
900
+ def turn_answer(response, asked, output, filter)
901
+ # HALTED BY A TOOL RESULT (`halt_when`): RubyLLM returns the Tool::Halt itself
902
+ # instead of a Message, and its `content` is the tool PAYLOAD — publishing it
903
+ # would ship the envelope to the customer as the answer. The turn is worth
904
+ # exactly the lead-in of the message that called the tool (the model's "vou te
905
+ # inscrever agora"), and nothing after: the backend already said the rest.
906
+ # Nothing streamed -> the tool's `halt_when.say`, when it declared one; else an
907
+ # empty turn, which is what the consumer suppresses. The lead-in still WINS —
908
+ # a model that introduced the escalation already said the right thing, and
909
+ # publishing both would deliver the message twice, which is the whole reason
910
+ # `halt_when` exists.
911
+ return halt_answer(response, output) if halted?(response)
912
+ # An :agent after-hook REPLACED the response. An explicit override outranks
913
+ # what the model streamed (the OutputValidator still sees the result).
914
+ return content_of(response) unless response.equal?(asked)
915
+ # The normal path: the message that ended the turn, as it was streamed and
916
+ # (when guardrails are on) redacted.
917
+ return output.candidate if output.candidate
918
+
919
+ # No message boundary was reported — a transport that does not implement
920
+ # `after_message`. Fall back to the whole turn's redacted text, else the raw
921
+ # response: the pre-boundary behaviour, kept as the floor.
922
+ filter ? filter.output : content_of(response)
923
+ end
924
+
925
+ # The lead-in when there is one; otherwise whatever the halting tool declared it
926
+ # wants the customer to get (`halt_when.say`). Never both.
927
+ def halt_answer(response, output)
928
+ lead = output.halt_text.to_s
929
+ return lead unless lead.strip.empty?
930
+
931
+ Insika::ToolDefinition.halt_say_of(content_of(response)).to_s
932
+ end
933
+
934
+ def halted?(response) = response.is_a?(RubyLLM::Tool::Halt)
935
+
936
+ def content_of(response) = response.respond_to?(:content) ? response.content : response.to_s
937
+
938
+ # The provider's REASONING (DeepSeek `reasoning_content`, Anthropic thinking
939
+ # blocks): RubyLLM parks it in `chunk.thinking`, NEVER in `chunk.content`, so it
940
+ # was being dropped on the floor — invisible in the Studio and in the trace. It
941
+ # rides the Event Stream as its OWN type (:thinking), and `/v1/responses` does not
942
+ # translate it BY DEFAULT: the deliberation is observability, not the answer.
943
+ #
944
+ # An agent may opt in (`edge_stream thinking: true`) — a product with a "thinking"
945
+ # panel wants it — and then the event is TAGGED `public: true` and the edge gives
946
+ # it the reasoning frame, never the answer's. The tag rides the event because
947
+ # `Responses.frame_for` is a pure static mapper with no agent in scope.
948
+ #
949
+ # Three deliberate omissions:
950
+ # · the guardrail filter is NOT applied — it accumulates the PERSISTED content
951
+ # (D3), and pushing reasoning through it would corrupt the turn's answer;
952
+ # · `timing.mark(:first_token)` stays on the content chunks — ttft is the
953
+ # PROVIDER's first token (item 34's baselines measure that, not the first
954
+ # thought, and not when TurnOutput publishes the answer);
955
+ # · nothing is persisted — the reasoning is not part of the conversation.
956
+ #
957
+ # Duck-typed like `usage_of`: a provider/fake with no thinking -> nothing to emit.
958
+ def emit_thinking(chunk, task, public: false)
959
+ return unless chunk.respond_to?(:thinking)
960
+
961
+ thought = chunk.thinking
962
+ text = thought.respond_to?(:text) ? thought.text : thought # RubyLLM::Thinking | String | nil
963
+ return if text.to_s.empty?
964
+
965
+ data = { delta: text.to_s }
966
+ data[:public] = true if public
967
+ emit(:thinking, data, task: task)
968
+ end
969
+
970
+ # Annotates the usage with the RESOLVED model-selection source (v2, §10):
971
+ # where the model came from (:chat/:agent/:platform_default) travels alongside
972
+ # the resolved model id (from the provider) into the terminal event/Telemetry,
973
+ # so billing/telemetry can attribute the turn to a config layer. nil usage
974
+ # (workflow / provider without counts) -> nothing to annotate.
975
+ def with_model_source(usage, selection)
976
+ return usage if usage.nil? || selection.nil?
977
+
978
+ usage[:model_source] = selection.source
979
+ usage[:model] ||= selection.model # falls back to the resolved id when the provider omits it
980
+ usage
981
+ end
982
+
983
+ # Token usage of the provider's response (RubyLLM::Message exposes
984
+ # input_tokens/output_tokens/cached_tokens/model_id). Duck-typed: a provider/
985
+ # fake with no counting -> nil (nothing to report). Shape compatible with the
986
+ # OpenAI Responses usage (input/output/total) + model, consumed by
987
+ # /v1/responses and Telemetry.
988
+ def usage_of(response)
989
+ return nil unless response.respond_to?(:input_tokens)
990
+
991
+ input = response.input_tokens.to_i
992
+ output = response.output_tokens.to_i
993
+ usage = { input_tokens: input, output_tokens: output, total_tokens: input + output }
994
+ if response.respond_to?(:cached_tokens) && response.cached_tokens
995
+ usage[:cached_tokens] = response.cached_tokens.to_i # cache_read_input_tokens
996
+ end
997
+ # §11 R3: prompt-cache WRITE tokens (Anthropic cache_creation_input_tokens),
998
+ # billed at ~1.25x. Reported so the first (write) turn vs later (read) turns
999
+ # are distinguishable in telemetry/usage.
1000
+ if response.respond_to?(:cache_creation_tokens) && response.cache_creation_tokens
1001
+ usage[:cache_creation_tokens] = response.cache_creation_tokens.to_i
1002
+ end
1003
+ usage[:model] = response.model_id.to_s if response.respond_to?(:model_id) && response.model_id
1004
+ usage
1005
+ end
1006
+
1007
+ def workflow_name(task)
1008
+ rebuild_command(task).payload["workflow"]
1009
+ end
1010
+
1011
+ # turn message: send_message -> payload.message; trigger_workflow ->
1012
+ # payload.input (the input becomes the "user" content and the workflow
1013
+ # argument).
1014
+ def extract_message(task)
1015
+ payload = rebuild_command(task).payload
1016
+ payload["message"] || payload["input"]
1017
+ end
1018
+
1019
+ def command_history(task)
1020
+ rebuild_command(task).payload["history"]
1021
+ end
1022
+
1023
+ def build_context_request(task, profile, state, resume_from)
1024
+ session = task.session_id ? @session_store.find(task.session_id) : nil
1025
+ state.session = session # create_chat reads it for the per-chat model pin (§10)
1026
+ hist = command_history(task)
1027
+ # `vars` reconciles the seam (the Request/Session provider already
1028
+ # called request.vars): session metadata + the explicit `history` in the
1029
+ # convention the Session provider consumes (vars["history"]).
1030
+ vars = (session&.vars || {}).dup
1031
+ vars["history"] = hist if hist
1032
+ # The single type is Insika::ContextRequest (Data); the explicit `history`
1033
+ # travels in vars["history"] (Session provider convention), not in a field
1034
+ # of its own.
1035
+ ContextRequest.new(profile: profile, message: state.message, session: session,
1036
+ checkpoint: resume_from, tenant: command_tenant(task), vars: vars)
1037
+ end
1038
+
1039
+ # :task_started payload. Carries the EXPLICIT command tenant (item 16 / P4) so
1040
+ # the observability convention can group by it — the one operator-set label that
1041
+ # is not derivable from the task itself. Omitted when absent: the terminal
1042
+ # events keep their shape and no consumer sees a null it never saw before. NOT
1043
+ # memory_tenant: that one falls back to the chat id (per-chat cardinality).
1044
+ def started_data(task, profile)
1045
+ data = { task_id: task.id, command: command_type(task), agent: profile&.id }
1046
+ tenant = command_tenant(task)
1047
+ data[:tenant] = tenant if tenant
1048
+ data
1049
+ end
1050
+
1051
+ # Command tenant (Command.build(..., tenant:) -> meta[:tenant],
1052
+ # command.rb). Absent -> nil (the MemoryStore applies DEFAULT_TENANT).
1053
+ def command_tenant(task)
1054
+ rebuild_command(task).meta["tenant"]
1055
+ end
1056
+
1057
+ # Who produced the message this turn is answering (MessageOrigin). Absent for an
1058
+ # ordinary turn — a customer typed it — and declared by the producer when not:
1059
+ # the engine delivering a delegation result, or a consumer that composed the
1060
+ # input out of context blocks. Validated where it enters (Commands::SendMessage).
1061
+ def command_origin(task)
1062
+ Coercion.presence(rebuild_command(task).payload["origin"])
1063
+ end
1064
+
1065
+ # Engine memory scope (D3): the Command's EXPLICIT tenant wins (multi-merchant
1066
+ # override); otherwise the SESSION (=chat) — engine-owner memory is per-chat.
1067
+ # Symmetric to the READ path (Memory provider). One-shot with no tenant -> nil
1068
+ # (_default). It is NOT the <request_context> tenant (that follows
1069
+ # command_tenant, prompt parity) — only the memory read/write scope.
1070
+ def memory_tenant(task)
1071
+ command_tenant(task) || task.session_id
1072
+ end
1073
+
1074
+ # Turn context (Phase 6/D2/G4): the ids the data-tools resolve via
1075
+ # {{ctx.*}} to emit X-Chat-Id/X-Store-Id/X-Agent-Id to /api/internal/*. They
1076
+ # come from the TURN, never from the model args (R2). chat_id = the session
1077
+ # (the /v1/responses adapter creates the session with id = user = chat.id);
1078
+ # tenant = the Command tenant (memory) OR chat_id (drop-in default); agent_id =
1079
+ # profile; store_id = the profile metadata (stable per store, from the pack).
1080
+ # Absent fields -> nil (the data-tool emits an empty header; in the pilot the
1081
+ # profile carries store_id). Generic: nothing here mentions achei-b2b (NF1).
1082
+ def build_turn_context(task, profile, state)
1083
+ {
1084
+ chat_id: task.session_id,
1085
+ agent_id: profile.id,
1086
+ tenant: state.tenant, # already = command_tenant || session_id (memory_tenant)
1087
+ store_id: profile.store_id,
1088
+ # RFC-0010: current delegation depth (0 for a top-level turn). Carried in
1089
+ # the child command's payload by run_subagent; read here so the child's OWN
1090
+ # spawn_subagent tool sees depth+1 and the runtime cap holds down the chain.
1091
+ delegation_depth: delegation_depth(task)
1092
+ }
1093
+ end
1094
+
1095
+ # Delegation depth of THIS turn (RFC-0010): the value run_subagent stamped in
1096
+ # the child command, or 0 for a top-level turn. Integer-coerced (JSON round-trip
1097
+ # of the persisted command may deliver a String).
1098
+ def delegation_depth(task)
1099
+ rebuild_command(task).payload["delegation_depth"].to_i
1100
+ end
1101
+
1102
+ # RFC-0010 R2: environment (model/thinking) inherits as DEFAULT — the child's
1103
+ # explicit value wins; when absent, seed from the parent's RESOLVED selection.
1104
+ # Capacity fields are untouched (R1: the child profile is used as-is). Returns
1105
+ # the child profile unchanged when there is nothing to inherit.
1106
+ def inherit_environment(child_profile, parent_state)
1107
+ sel = parent_state.model_selection
1108
+ return child_profile if sel.nil?
1109
+
1110
+ model = child_profile.model || sel.model
1111
+ provider = child_profile.provider || sel.provider
1112
+ params = child_profile.params.dup # build stringified it => string keys
1113
+ inherited_thinking = (sel.params || {})[:thinking]
1114
+ params["thinking"] = inherited_thinking if !params.key?("thinking") && !inherited_thinking.nil?
1115
+
1116
+ return child_profile if model == child_profile.model &&
1117
+ provider == child_profile.provider &&
1118
+ params == child_profile.params
1119
+
1120
+ child_profile.with(model: model, provider: provider, params: params)
1121
+ end
1122
+
1123
+ # Single validation path for a delegation (RFC-0010) — shared by run_subagent
1124
+ # and the fan-out run_subagents. `task` is {agent, message} (string OR symbol
1125
+ # keys — the model's args arrive string-keyed). Returns a resolved plan
1126
+ # { agent:, profile:, message:, depth: } or { agent:, error: } (the agent name is
1127
+ # kept even on error so a fan-out result keeps its slot labeled).
1128
+ def plan_subagent(task, parent_state)
1129
+ agent = (task["agent"] || task[:agent]).to_s
1130
+ message = (task["message"] || task[:message]).to_s
1131
+
1132
+ # Gate = the PARENT's subagents allowlist (a capacity field — never inherited).
1133
+ allowed = Array(parent_state.profile.subagents).map(&:to_s)
1134
+ return { agent: agent, error: "agent '#{agent}' is not in this agent's subagents allowlist" } unless allowed.include?(agent)
1135
+
1136
+ # Runtime depth guard (belt-and-suspenders; SubagentGraph is the primary,
1137
+ # definition-time check). parent depth from its turn context, +1 for the child.
1138
+ cap = SubagentGraph.depth_cap
1139
+ depth = (parent_state.turn_context&.dig(:delegation_depth) || 0) + 1
1140
+ return { agent: agent, error: "subagent depth #{depth} exceeds cap #{cap}" } if depth > cap
1141
+
1142
+ profile = @profiles[agent]
1143
+ return { agent: agent, error: "agent '#{agent}' not configured" } if profile.nil?
1144
+
1145
+ { agent: agent, profile: inherit_environment(profile, parent_state), message: message, depth: depth }
1146
+ end
1147
+
1148
+ # Fan-out barrier: spawn ALL valid children first (non-blocking), THEN await ALL.
1149
+ # Spawning before awaiting is what makes them concurrent — each child spends its
1150
+ # time on the provider HTTP wait, and those waits overlap on the reactor. Invalid
1151
+ # plans keep their ordered slot as an { agent:, error: } result.
1152
+ def spawn_all_and_project(plans, parent_state)
1153
+ spawned = plans.map do |plan|
1154
+ next plan if plan[:error]
1155
+
1156
+ session_id, child_task = create_child(plan[:profile], plan[:message], plan[:depth], parent_state, async: false)
1157
+ spawn(child_task, profile: plan[:profile])
1158
+ { agent: plan[:agent], task_id: child_task.id, session_id: session_id }
1159
+ end
1160
+
1161
+ spawned.each { |s| @running[s[:task_id]]&.wait unless s[:error] }
1162
+ spawned.map do |s|
1163
+ next { agent: s[:agent], error: s[:error] } if s[:error]
1164
+
1165
+ # label each result with its agent so the model can tell the N apart.
1166
+ project_child_result(s[:task_id], s[:session_id], s[:agent], parent_state).merge(agent: s[:agent])
1167
+ end
1168
+ end
1169
+
1170
+ # Creates the isolated child session (linked to the parent) + child task.
1171
+ # Shared by the sync and async paths. Emits :subagent_started correlated to the
1172
+ # PARENT task. -> [child_session_id, child_task].
1173
+ def create_child(child_profile, message, depth, parent_state, async:, delegation_id: nil)
1174
+ child_session_id = "sub-#{SecureRandom.uuid}"
1175
+ @session_store.create(
1176
+ id: child_session_id,
1177
+ vars: { "parent_session_id" => parent_state.task.session_id,
1178
+ "parent_task_id" => parent_state.task.id, "delegation_depth" => depth }
1179
+ )
1180
+ payload = { "agent" => child_profile.id, "message" => message,
1181
+ "session_id" => child_session_id, "delegation_depth" => depth }
1182
+ # Async children carry their delegation id in the command payload so the
1183
+ # terminal hook (finalize_delegation) is O(1) — a normal turn has no marker and
1184
+ # skips the delegation store entirely (no per-turn O(n) scan).
1185
+ payload["delegation_id"] = delegation_id if delegation_id
1186
+ command = Insika::Command.build(:send_message, payload).to_h
1187
+ child_task = @task_store.create(command: command, session_id: child_session_id)
1188
+
1189
+ emit(:subagent_started,
1190
+ { agent: child_profile.id, parent_task_id: parent_state.task.id,
1191
+ child_session_id: child_session_id, depth: depth, async: async },
1192
+ task: parent_state.task)
1193
+ [child_session_id, child_task]
1194
+ end
1195
+
1196
+ # SYNC (Fase 1): spawns the child and AWAITS it on the parent's fiber, then
1197
+ # projects the terminal content. Direct `spawn` (not spawn_in_session): the
1198
+ # child session is brand-new, so there is no SessionActor contention — the child
1199
+ # is parented at turn_parent and the parent yields cooperatively on `wait`.
1200
+ def spawn_and_await_child(child_profile, message, depth, parent_state)
1201
+ child_session_id, child_task = create_child(child_profile, message, depth, parent_state, async: false)
1202
+ spawn(child_task, profile: child_profile)
1203
+ @running[child_task.id]&.wait
1204
+ project_child_result(child_task.id, child_session_id, child_profile.id, parent_state)
1205
+ end
1206
+
1207
+ # ASYNC (Fase 2): persists a Delegation, spawns the child NON-blocking, and
1208
+ # returns a dispatch ack immediately — the parent turn ends without waiting. The
1209
+ # child's terminal hook (finalize_delegation) delivers the result later, as a
1210
+ # NEW turn on the parent session.
1211
+ def dispatch_async_child(child_profile, message, depth, parent_state)
1212
+ delegation_id = SecureRandom.uuid
1213
+ child_session_id, child_task =
1214
+ create_child(child_profile, message, depth, parent_state, async: true, delegation_id: delegation_id)
1215
+ @delegation_store.create(
1216
+ id: delegation_id,
1217
+ parent_task_id: parent_state.task.id, parent_session_id: parent_state.task.session_id,
1218
+ parent_agent: parent_state.profile.id, child_agent: child_profile.id,
1219
+ child_task_id: child_task.id, child_session_id: child_session_id, depth: depth
1220
+ )
1221
+ spawn(child_task, profile: child_profile)
1222
+ { dispatched: child_task.id, agent: child_profile.id, session_id: child_session_id }
1223
+ end
1224
+
1225
+ # Child result = last `assistant` message of the child session (R3), or the
1226
+ # terminal error if the child turn failed. Same projection as the A2A edge.
1227
+ def project_child_result(child_task_id, child_session_id, agent_id, parent_state)
1228
+ task = @task_store.find(child_task_id)
1229
+ if task && task.status.to_s == "failed"
1230
+ err = child_terminal_error(task)
1231
+ emit(:subagent_completed,
1232
+ { agent: agent_id, child_session_id: child_session_id, state: "failed" },
1233
+ task: parent_state.task)
1234
+ return { error: "subagent '#{agent_id}' failed: #{err || 'unknown error'}" }
1235
+ end
1236
+
1237
+ emit(:subagent_completed,
1238
+ { agent: agent_id, child_session_id: child_session_id, state: "completed" },
1239
+ task: parent_state.task)
1240
+ { text: child_final_text(child_session_id).to_s, session_id: child_session_id }
1241
+ end
1242
+
1243
+ def child_final_text(child_session_id)
1244
+ session = @session_store.find(child_session_id)
1245
+ msg = session&.messages&.reverse&.find { |m| (m["role"] || m[:role]).to_s == "assistant" }
1246
+ msg && (msg["content"] || msg[:content])
1247
+ end
1248
+
1249
+ def child_terminal_error(task)
1250
+ exec = task.executions.last
1251
+ return nil unless exec && exec.outcome.to_s == "failed"
1252
+
1253
+ exec.error && (exec.error["message"] || exec.error[:message])
1254
+ end
1255
+
1256
+ # RFC-0010 Fase 2 — terminal hook: when a turn ends (success OR failure), if the
1257
+ # task is the child of an ASYNC delegation, capture its result and deliver it to
1258
+ # the parent. Fires for both a normal completion and a resumed one (recovery),
1259
+ # so it needs no live watcher fiber. No-op without a delegation_store or when the
1260
+ # task is not a delegation child. Best-effort: a failure here must NOT re-fail an
1261
+ # already-committed child turn — swallow (recovery re-drives from the record).
1262
+ def finalize_delegation(child_task)
1263
+ return unless @delegation_store
1264
+
1265
+ # Fresh read: the snapshot the hook passes predates transition(:completed/
1266
+ # :failed); the store is the single source of truth for terminal state + the
1267
+ # command marker.
1268
+ child_id = child_task.respond_to?(:id) ? child_task.id : child_task
1269
+ child = @task_store.find(child_id)
1270
+ # Cheap gate: only async delegation children carry a delegation_id in the
1271
+ # command payload — a normal turn skips the store entirely (no O(n) scan).
1272
+ deleg_id = child && rebuild_command(child).payload["delegation_id"]
1273
+ return unless deleg_id
1274
+
1275
+ deleg = @delegation_store.find(deleg_id)
1276
+ return if deleg.nil? || deleg.status == :delivered
1277
+
1278
+ if deleg.status == :dispatched
1279
+ if child.status.to_s == "failed"
1280
+ @delegation_store.mark_completed(deleg.id, error: child_terminal_error(child) || "unknown error")
1281
+ else
1282
+ @delegation_store.mark_completed(deleg.id, result: child_final_text(deleg.child_session_id).to_s)
1283
+ end
1284
+ end
1285
+ deliver_delegation(@delegation_store.find(deleg.id))
1286
+ rescue Insika::Error
1287
+ nil # best-effort: never re-fail a committed child turn (recovery re-drives).
1288
+ end
1289
+
1290
+ # Delivers a captured delegation as a NEW turn on the PARENT session. The claim
1291
+ # (completed -> delivered) makes this AT-MOST-ONCE: only the caller that wins the
1292
+ # transition spawns the delivery turn (the hook and recovery may both fire).
1293
+ # spawn_in_session routes through the parent's SessionActor FIFO — that is what
1294
+ # makes it a new turn "when idle" (queued behind any in-flight parent turn),
1295
+ # preserving role alternation + prompt cache.
1296
+ def deliver_delegation(deleg)
1297
+ return unless @delegation_store.claim_delivery(deleg.id)
1298
+
1299
+ profile = @profiles[deleg.parent_agent]
1300
+ # The parent agent vanished (deleted mid-flight): nothing to deliver to. The
1301
+ # record stays :delivered (claimed) so recovery does not loop on it.
1302
+ return if profile.nil?
1303
+
1304
+ message = format_delegation_message(deleg)
1305
+ command = Insika::Command.build(
1306
+ :send_message,
1307
+ # `origin: engine` — this "user" message is Insika writing to itself. Without
1308
+ # it a report reads a delegation result as something the customer said.
1309
+ { "agent" => deleg.parent_agent, "message" => message,
1310
+ "session_id" => deleg.parent_session_id, "delegation_id" => deleg.id,
1311
+ "origin" => Insika::MessageOrigin::ENGINE }
1312
+ ).to_h
1313
+ task = @task_store.create(command: command, session_id: deleg.parent_session_id)
1314
+ emit(:subagent_delivered,
1315
+ { delegation_id: deleg.id, agent: deleg.child_agent,
1316
+ child_session_id: deleg.child_session_id, state: deleg.error ? "failed" : "completed" },
1317
+ task: task)
1318
+ spawn_in_session(task, profile: profile)
1319
+ end
1320
+
1321
+ # The synthetic message the parent turn receives. A clear, self-describing note
1322
+ # so the parent agent knows a delegated subtask returned (and can relay it).
1323
+ def format_delegation_message(deleg)
1324
+ if deleg.error
1325
+ "[subagent:#{deleg.child_agent}] delegated task FAILED: #{deleg.error}"
1326
+ else
1327
+ "[subagent:#{deleg.child_agent}] delegated task completed. Result:\n\n#{deleg.result}"
1328
+ end
1329
+ end
1330
+
1331
+ # The real Request: command (for the WorkflowAllowlist), context
1332
+ # (Context before Policy), candidate_tools (registry Entries, UNfiltered) and
1333
+ # candidate_skills (from the CATALOG).
1334
+ def policy_request(profile, task, state)
1335
+ Insika::Policy::PolicyRequest.new(
1336
+ profile: profile,
1337
+ command: rebuild_command(task),
1338
+ context: state.context,
1339
+ candidate_tools: @tool_registry.entries,
1340
+ candidate_skills: @skill_catalog.effective(profile.skills)
1341
+ )
1342
+ end
1343
+
1344
+ # The Task persists the Command as a Hash; the WorkflowAllowlist needs
1345
+ # a Command with #type (Symbol) and #payload. §11 B2: the SINGLE point that
1346
+ # reconciles the string||symbol keys of the persisted command — payload/meta
1347
+ # keys are stringified ONCE here, so every reader (command_type/workflow_name/
1348
+ # extract_message/command_history/command_tenant) works with string keys.
1349
+ def rebuild_command(task)
1350
+ cmd = task.command
1351
+ Insika::Command.new(
1352
+ type: (cmd["type"] || cmd[:type]).to_s.to_sym,
1353
+ payload: normalize_keys(cmd["payload"] || cmd[:payload]),
1354
+ meta: normalize_keys(cmd["meta"] || cmd[:meta])
1355
+ )
1356
+ end
1357
+
1358
+ # Shallow key stringification (nil -> {}). The persisted command comes
1359
+ # string-keyed from the TaskStore; this only matters for a symbol-keyed
1360
+ # command that bypassed it (fakes/tests).
1361
+ def normalize_keys(hash)
1362
+ (hash || {}).each_with_object({}) { |(k, v), acc| acc[k.to_s] = v }
1363
+ end
1364
+
1365
+ # Stage-3-tail tool assembly — delegated to ToolAssembly (§11 B5). Kept as
1366
+ # thin private methods so the existing spec contract (executor.send(:...))
1367
+ # stays intact and run_pipeline reads unchanged.
1368
+ def resolve_capabilities(profile, context) = @tool_assembly.resolve_capabilities(profile, context)
1369
+ def assemble_tool_instances(allowed, state) = @tool_assembly.assemble_tool_instances(allowed, state)
1370
+
1371
+ def wrap_tools(tools, state, skip_side_effects = [])
1372
+ @tool_assembly.wrap_tools(tools, state, skip_side_effects)
1373
+ end
1374
+
1375
+ # Stage boundary: drains the mailbox and, if the operator requested a pause,
1376
+ # SUSPENDS the turn in :paused until :resume. Cooperative — never in the
1377
+ # middle of an operation. NOT called at stage 8 (forbidden window).
1378
+ # :cancel during the wait becomes CancelledError (top single capture);
1379
+ # :timeout becomes TimeoutError. The turn's initial checkpoint was already
1380
+ # written, so a kill -9 in :paused is resumable.
1381
+ def drain_and_maybe_suspend(task, actor)
1382
+ actor.drain!
1383
+ return unless actor.pause_requested?
1384
+
1385
+ @task_store.transition(task.id, to: :paused)
1386
+ emit(:task_paused, { task_id: task.id }, task: task)
1387
+ actor.await(reason: :paused) # blocks until :resume (or raises on :cancel/:timeout)
1388
+ @task_store.transition(task.id, to: :running)
1389
+ emit(:task_resumed, { task_id: task.id }, task: task)
1390
+ end
1391
+
1392
+ # Checkpoint of the turn's initial state (see the call in run_pipeline). Only
1393
+ # on the 1st turn of a new task: on resume the turn checkpoint already exists
1394
+ # (does not re-save — the CheckpointStore's monotonicity would raise). It emits
1395
+ # NO event (:checkpoint_created is stage 8's only) and touches no side-effects.
1396
+ def save_initial_checkpoint(task, profile, state)
1397
+ return unless @checkpoint_store.find(task.id, turn: state.turn).nil?
1398
+
1399
+ @checkpoint_store.save(Insika::Checkpoint.new(
1400
+ task_id: task.id, turn: state.turn, session_id: task.session_id,
1401
+ agent_id: profile.id, messages: flatten_history(state.context.history),
1402
+ completed_side_effects: [], created_at: Time.now.utc.iso8601
1403
+ ))
1404
+ end
1405
+
1406
+ # GRACEFUL halt (RFC-0009 §3.1): a Middleware short-circuited with a safe reply.
1407
+ # The turn COMPLETES — same stages 8-9 as a normal turn — but the "assistant
1408
+ # content" is the guardrail's safe response, produced with ZERO LLM calls. The
1409
+ # order mirrors a real turn so both the /v1/responses consumer (which reads the
1410
+ # text off :content deltas) and the Studio viewer render it: audit -> safe text
1411
+ # -> persist -> terminal.
1412
+ def complete_with_halt(task, profile, state)
1413
+ content = state.halt_response.to_s
1414
+ state.response_content = content
1415
+
1416
+ if (block = state.guardrail_block)
1417
+ emit(:guardrail_blocked, {
1418
+ task_id: task.id, category: block[:category], source: block[:source],
1419
+ action: block[:action], detail: block[:detail]
1420
+ }, task: task)
1421
+ end
1422
+ emit(:content, { delta: content }, task: task) unless content.empty?
1423
+ # An EDGE-blocked turn (rate limit / token ceiling, item 33) completes but
1424
+ # stays OUT of the session history: a flood at the wall must not bloat the
1425
+ # session nor evict real conversation from the context budget — the
1426
+ # :guardrail_blocked event is the audit trail. Content-guardrail blocks
1427
+ # keep persisting (RFC-0009: the refusal is part of the conversation).
1428
+ # The reply is the guardrail's, produced with zero LLM calls — so it is NOT the
1429
+ # agent talking, and a report that counts it as the agent repeating itself is
1430
+ # reading the engine's own canned text (the `safe_reply` finding exists exactly
1431
+ # because that text is otherwise indistinguishable in the transcript).
1432
+ persist_turn(task, profile, state, content, reply_origin: MessageOrigin::ENGINE,
1433
+ session: state.guardrail_block&.[](:source) != "edge")
1434
+ emit(:task_completed, { task_id: task.id, content: content, usage: state.usage }, task: task)
1435
+ end
1436
+
1437
+ # Emits one :guardrail_flagged per flag the OutputValidator appended in
1438
+ # after_task (audit only — the turn already completed). Reads a plain Array off
1439
+ # the state, keeping the Executor decoupled from Safety.
1440
+ def emit_guardrail_flags(task, state)
1441
+ return unless state.respond_to?(:guardrail_flags)
1442
+
1443
+ Array(state.guardrail_flags).each do |flag|
1444
+ emit(:guardrail_flagged, {
1445
+ task_id: task.id, category: flag[:category], source: flag[:source], detail: flag[:detail]
1446
+ }, task: task)
1447
+ end
1448
+ end
1449
+
1450
+ # Stage 8: FIXED order checkpoint -> session -> task. If it crashes
1451
+ # between writes, the worst case is a new checkpoint with the task :running ->
1452
+ # Recovery re-executes the already-saved turn (safe thanks to the side-effect
1453
+ # recording).
1454
+ #
1455
+ # CHECKPOINT vs SESSION — the two stores DIVERGE by design (§11 R2c):
1456
+ # · Checkpoint.messages = flatten_history(context.history) + new_messages,
1457
+ # i.e. "what the model actually SAW this turn" AFTER budget eviction
1458
+ # (context.history is the post-budget assembly). It is the deterministic
1459
+ # replay tape for Recovery: resuming from it reproduces the exact prompt.
1460
+ # It is per-task and pruned to keep: 1 (only the latest matters for resume).
1461
+ # · SessionStore = the INTEGRAL source of truth: append-only, never evicted,
1462
+ # the full human-readable transcript (viewer, audit, next turns' raw input).
1463
+ # So a long session legitimately has a Checkpoint SHORTER than the Session:
1464
+ # that is not drift to reconcile — it is the point. Do NOT "fix" the checkpoint
1465
+ # to carry the full history (it would defeat the budget) nor evict the session.
1466
+ def persist_turn(task, profile, state, content, session: true, reply_origin: nil)
1467
+ new_messages = turn_transcript(state, content, origin: command_origin(task), reply_origin: reply_origin)
1468
+ transcript = flatten_history(state.context.history) + new_messages
1469
+
1470
+ @checkpoint_store.save(Insika::Checkpoint.new(
1471
+ task_id: task.id, turn: state.turn + 1, session_id: task.session_id,
1472
+ agent_id: profile.id, messages: transcript,
1473
+ completed_side_effects: [], created_at: Time.now.utc.iso8601
1474
+ ))
1475
+
1476
+ # session only when the turn is from a persisted session; one-shot/history
1477
+ # do not persist TO THE SESSION (but always checkpoint). `session: false` is
1478
+ # the edge-blocked halt (see complete_with_halt).
1479
+ @session_store.append_messages(task.session_id, new_messages) if session && task.session_id
1480
+
1481
+ # finish_execution (closes the Execution) BEFORE transition(:completed) —
1482
+ # transition without error: does not close, so the finish is needed here.
1483
+ @task_store.finish_execution(task.id, outcome: :completed)
1484
+ @task_store.transition(task.id, to: :completed)
1485
+ # prune is best-effort cleanup: a failure here must NOT re-fail an
1486
+ # already-committed turn (the task is already :completed and durable).
1487
+ # Swallow.
1488
+ begin
1489
+ @checkpoint_store.prune(task.id, keep: 1)
1490
+ rescue Insika::StoreError
1491
+ nil
1492
+ end
1493
+
1494
+ emit(:checkpoint_created, { task_id: task.id, turn: state.turn + 1 }, task: task)
1495
+
1496
+ # RFC-0010 Fase 2: if this completed turn is an ASYNC delegation child,
1497
+ # deliver its result to the parent as a NEW turn. No-op for a normal turn
1498
+ # (not a delegation child) or without a delegation_store.
1499
+ finalize_delegation(task)
1500
+
1501
+ # RFC-0011 §6.5: if this turn CAME IN through a Shape B channel, its answer
1502
+ # has to travel out of band. Same terminal hook, next door to the delegation
1503
+ # one, for the same reason: it fires for a fresh turn and a recovered one.
1504
+ finalize_channel_delivery(task, content)
1505
+ end
1506
+
1507
+ # Records the answer in the outbox and dispatches it. The discriminator is the
1508
+ # turn's TRANSPORT (`channel:<id>` on the persisted command), not the session:
1509
+ # a session belongs to the channel forever, but a message an operator types into
1510
+ # the Studio playground against that same session must not reach the customer.
1511
+ # Human handoff is not a product feature (`FOLLOWUP §14.6`), and it would be a
1512
+ # surprising way to acquire one.
1513
+ #
1514
+ # The consequence, stated rather than discovered later: a turn the ENGINE
1515
+ # spawned on a channel session — an async delegation result delivered as a new
1516
+ # turn — is not delivered either. There is no consumer for that yet; when there
1517
+ # is, the fix is to give those turns the channel transport, not to widen this.
1518
+ #
1519
+ # Best-effort: the turn is already committed and durable, and a delivery problem
1520
+ # must never re-fail it.
1521
+ def finalize_channel_delivery(task, content)
1522
+ return unless @channel_delivery
1523
+
1524
+ channel_id = channel_transport(task)
1525
+ return unless channel_id
1526
+
1527
+ delivery = @channel_delivery.record(task: task, channel_id: channel_id, content: content)
1528
+ return unless delivery
1529
+
1530
+ dispatch_delivery(delivery.id)
1531
+ rescue Insika::Error
1532
+ nil
1533
+ end
1534
+
1535
+ # The POST goes out on the SUPERVISOR, never on the turn's fiber: a bounded
1536
+ # retry against a third party would otherwise hold the session's FIFO — the
1537
+ # customer's next message would wait on their previous answer's delivery.
1538
+ # Non-serving (boot sweep, specs) delivers inline, where waiting is what the
1539
+ # caller wants.
1540
+ def dispatch_delivery(delivery_id)
1541
+ return @channel_delivery.deliver(delivery_id) unless @supervised
1542
+
1543
+ turn_parent.async do |t|
1544
+ t.annotate("outbox:#{delivery_id}")
1545
+ @channel_delivery.deliver(delivery_id)
1546
+ end
1547
+ end
1548
+
1549
+ # `channel:<id>` -> "<id>"; anything else -> nil. The transport is persisted with
1550
+ # the command, so a turn resumed after a crash still knows where it came from.
1551
+ def channel_transport(task)
1552
+ transport = rebuild_command(task).meta["transport"].to_s
1553
+ transport.start_with?("channel:") ? transport.delete_prefix("channel:") : nil
1554
+ end
1555
+
1556
+ # Truncation cap for a persisted `role: tool` content (§11 R1): the transcript
1557
+ # keeps the loop coherent; the FULL result lives in the ToolTraceStore (viewer).
1558
+ TOOL_CONTENT_CAP = 4_000
1559
+
1560
+ # The turn's messages in the ADDITIVE string-keyed format (§11 R1). Prefers the
1561
+ # real chat transcript (`chat.messages.drop(baseline)`) so tool calls/results
1562
+ # survive between turns; falls back to the {user, assistant} pair when the chat
1563
+ # did not record the turn (workflow, graceful halt, or the specs' FakeChat).
1564
+ # The final assistant text is the REDACTED `content` (output_filter, RFC-0009 D3),
1565
+ # never the raw text the gem stored.
1566
+ # `origin` (MessageOrigin) travels on the turn's Command and is stamped on the
1567
+ # message it describes: the INCOMING one. It is absent for an ordinary turn, and
1568
+ # present when the engine wrote the text itself (an async delegation result
1569
+ # delivered as a new turn) or when the consumer declared that it composed it.
1570
+ # The reply's origin is not a parameter — the model wrote it, unless a guardrail
1571
+ # short-circuited, which `complete_with_halt` says explicitly.
1572
+ def turn_transcript(state, content, origin: nil, reply_origin: nil)
1573
+ recorded = recorded_turn_messages(state)
1574
+ if recorded.empty?
1575
+ return [MessageOrigin.stamp({ "role" => "user", "content" => state.message.to_s }, origin),
1576
+ MessageOrigin.stamp({ "role" => "assistant", "content" => content.to_s }, reply_origin)]
1577
+ end
1578
+
1579
+ recorded[0] = MessageOrigin.stamp(recorded[0], origin) if recorded[0]["role"] == "user"
1580
+ recorded[-1] = recorded[-1].merge("content" => content.to_s) if recorded.last["role"] == "assistant"
1581
+ recorded
1582
+ end
1583
+
1584
+ # Slices the chat's messages added DURING this turn and serializes them.
1585
+ # [] when there is no recorded transcript (baseline nil / no #messages).
1586
+ def recorded_turn_messages(state)
1587
+ chat = state.chat
1588
+ baseline = state.chat_baseline
1589
+ return [] unless chat && baseline && chat.respond_to?(:messages)
1590
+
1591
+ Array(chat.messages).drop(baseline).filter_map { |m| serialize_chat_message(m) }
1592
+ end
1593
+
1594
+ # A RubyLLM::Message (duck-typed) -> string-keyed Hash. Assistant carries
1595
+ # "tool_calls" only when present; tool carries "tool_call_id" + a clipped content.
1596
+ def serialize_chat_message(msg)
1597
+ role = msg_field(msg, :role).to_s
1598
+ content = msg_field(msg, :content).to_s
1599
+ case role
1600
+ when "assistant"
1601
+ calls = serialize_tool_calls(msg_field(msg, :tool_calls))
1602
+ h = { "role" => "assistant", "content" => content }
1603
+ h["tool_calls"] = calls unless calls.empty?
1604
+ h
1605
+ when "tool"
1606
+ { "role" => "tool", "tool_call_id" => msg_field(msg, :tool_call_id).to_s,
1607
+ "content" => clip_tool_content(content) }
1608
+ else
1609
+ { "role" => role, "content" => content }
1610
+ end
1611
+ end
1612
+
1613
+ # RubyLLM keeps tool_calls as {id => ToolCall}; tolerate an Array too. -> [{id,name,arguments}].
1614
+ def serialize_tool_calls(tool_calls)
1615
+ return [] if tool_calls.nil?
1616
+
1617
+ list = tool_calls.is_a?(Hash) ? tool_calls.values : Array(tool_calls)
1618
+ list.filter_map do |tc|
1619
+ next nil unless tc
1620
+
1621
+ { "id" => msg_field(tc, :id).to_s, "name" => msg_field(tc, :name).to_s,
1622
+ "arguments" => msg_field(tc, :arguments) || {} }
1623
+ end
1624
+ end
1625
+
1626
+ # Reads a field off a Message/ToolCall (method) OR a Hash (sym|string key).
1627
+ def msg_field(obj, key)
1628
+ return obj.public_send(key) if obj.respond_to?(key)
1629
+
1630
+ obj[key] || obj[key.to_s] if obj.respond_to?(:[])
1631
+ end
1632
+
1633
+ def clip_tool_content(str)
1634
+ return str if str.length <= TOOL_CONTENT_CAP
1635
+
1636
+ "#{str[0, TOOL_CONTENT_CAP]}…(truncated — full result in the viewer)"
1637
+ end
1638
+
1639
+ # context.history may carry "eviction units" (an assistant+tool_results cycle
1640
+ # grouped as one Array by the Session provider, §11 R1). Checkpoints store a
1641
+ # FLAT list — the provider regroups on read. Flatten one level; message Hashes
1642
+ # are untouched.
1643
+ def flatten_history(history) = Array(history).flatten(1)
1644
+
1645
+ # Stage 6 (factory): the ONLY point that touches the gem. lazy require,
1646
+ # confined — not covered by unit (factory line). It also loads the system
1647
+ # builtins (load_skill/tool_search/remember) that the ChatBuilder assembles at
1648
+ # stage 5 — lazy, so the core installs without ruby_llm.
1649
+ def create_chat(profile, state)
1650
+ require "ruby_llm"
1651
+ require_relative "tools/load_skill"
1652
+ require_relative "tools/tool_search"
1653
+ require_relative "tools/remember"
1654
+ require_relative "tools/subagent"
1655
+ require_relative "tools/subagents"
1656
+ # v2 resolution (§10): Chat pin > Agent model > platform default, model_policy
1657
+ # enforced, fallback chain resolved. Kept on the state for telemetry (usage).
1658
+ selection = @model_resolver.resolve(profile: profile, session: state.session)
1659
+ state.model_selection = selection
1660
+ chat = (@llm || RubyLLM).chat(
1661
+ model: selection.model,
1662
+ provider: selection.provider,
1663
+ assume_model_exists: selection.assume_model_exists?
1664
+ )
1665
+ selection.apply_params(chat) # temperature/max_tokens/thinking (per-agent, §10)
1666
+ chat
1667
+ end
1668
+
1669
+ # Single emitter: an Event with meta and a monotonic seq per task. @seqs is not
1670
+ # cleared at the end of the task — the resume (new Execution) continues the
1671
+ # numbering (reliable replay).
1672
+ def emit(type, data, task:)
1673
+ @event_stream.emit(Insika::Event.new(
1674
+ type: type, data: data,
1675
+ meta: { task_id: task.id, session_id: task.session_id,
1676
+ seq: (@seqs[task.id] += 1), at: Time.now.utc.iso8601 }
1677
+ ))
1678
+ end
1679
+ end
1680
+ end