package execution import "../access" import "../agent" import "../conversation" import "../provider" import "../sandbox" import "../sessionstore" import "../tool" import "core:mem" import "core:strings" import "core:sync" import "core:thread" import "core:time" MAILBOX_ITEMS :: 64 MAILBOX_BYTES :: 4 * 1024 * 1024 SNAPSHOT_BYTES :: 32 * 1024 * 1024 CONFIG_BYTES :: 1024 * 1024 TOOL_OUTPUT_BYTES :: 64 * 1024 OUTPUT_ALLOCATION_BYTES :: 128 * 1024 Event_Sink :: struct { data: rawptr, emit: proc(data: rawptr, event: agent.Event) } Executor_Config :: struct { instructions: string, projection_limits: conversation.Projection_Limits, native: access.Service, process: sandbox.Service, tool_timeout: time.Duration, // Zero selects 120 seconds; positive <= 120 seconds. } // Address-stable, owner-thread-only. Root service data/allocators outlive close. // init_executor freezes a copy of instructions and registry definitions/procedures. Executor :: struct { runtime: ^Runtime, allocator: mem.Allocator, config_budget: Budget, config: Executor_Config, definitions: []provider.Tool_Definition, entries: []tool.Definition, sink: Event_Sink, owner: int, active, pending: ^Job, entered, stopping, shutdown_saved, shutdown_failed: bool, last_error: conversation.Error, active_model: provider.Adapter, // Frozen at Turn_Started, not per worker/follow-up. } Job_Kind :: enum { Model, Tool, Save } Job :: struct { kind: Job_Kind, allocator: mem.Allocator, snapshot_budget, output_budget: Budget, model: provider.Adapter, capabilities: provider.Capabilities, enforce_capabilities: bool, store: sessionstore.Store, request: provider.Request, identity: conversation.Request_Identity, call: conversation.Tool_Call, selection: conversation.Selection, definition: tool.Definition, tool_context: tool.Context, session: conversation.Session, checkpoint: agent.Checkpoint, thread: ^thread.Thread, mutex: sync.Mutex, changed: sync.Cond, items: [MAILBOX_ITEMS]^Envelope, head, count, bytes: int, cancelled, released, terminal_seen, protocol_failed, setup_failed: bool, terminal: provider.Event, final_usage: provider.Usage, served_model: [conversation.MAX_IDENTIFIER_BYTES]byte, served_model_count: int, result: tool.Result, store_error: sessionstore.Error, } init_executor :: proc(value: ^Executor, runtime: ^Runtime, config: Executor_Config, sink: Event_Sink, allocator: mem.Allocator) -> conversation.Error { if value.runtime != nil || runtime == nil || runtime.executor != nil || runtime.services.identities == nil || runtime.services.identity_mutex == nil || runtime.agent.phase != .Idle || len(runtime.agent.pending.items) != 0 || !conversation.valid_session_id(runtime.conversation.id) || runtime.conversation.revision == 0 || !conversation.valid_selection(runtime.conversation.selection) || runtime.services.clock.wall == nil || runtime.services.clock.monotonic == nil || runtime.services.model.run == nil || (runtime.services.checkpoint_policy == .Durable && runtime.services.store.save == nil) || allocator.procedure == nil || !conversation.valid_text(config.instructions, 64 * 1024) || config.tool_timeout < 0 || config.tool_timeout > 120 * time.Second || !conversation.valid_text(config.native.id, conversation.MAX_IDENTIFIER_BYTES) || !conversation.valid_text(config.native.description, 64 * 1024) || !conversation.valid_text(config.process.id, conversation.MAX_IDENTIFIER_BYTES) || !conversation.valid_text(config.process.description, 64 * 1024) || config.projection_limits.max_bytes <= 0 || config.projection_limits.max_bytes > SNAPSHOT_BYTES || config.projection_limits.max_messages <= 0 || config.projection_limits.max_content_items <= 0 { return .Invalid_State } for turn in runtime.conversation.turns { if turn.outcome == .Active do return .Invalid_State } for request in runtime.conversation.requests { if request.outcome == .Active do return .Invalid_State } value^ = {runtime = runtime, allocator = allocator, owner = sync.current_thread_id(), sink = sink, config_budget = {backing = allocator, limit = CONFIG_BYTES}, config = config} value.config.instructions = "" value.config.native.id = ""; value.config.native.description = "" value.config.process.id = ""; value.config.process.description = "" committed := false defer { if !committed do destroy_executor(value) } a := budget_allocator(&value.config_budget) text, allocation := strings.clone(config.instructions, a) if allocation != nil do return .Allocation value.config.instructions = text value.config.native.id, allocation = strings.clone(config.native.id, a) if allocation != nil do return .Allocation value.config.native.description, allocation = strings.clone(config.native.description, a) if allocation != nil do return .Allocation value.config.process.id, allocation = strings.clone(config.process.id, a) if allocation != nil do return .Allocation value.config.process.description, allocation = strings.clone(config.process.description, a) if allocation != nil do return .Allocation if value.config.tool_timeout == 0 do value.config.tool_timeout = 120 * time.Second count := 0 if runtime.services.tools != nil do count = len(runtime.services.tools.entries) if count > 128 do return .Limit value.entries, allocation = make([]tool.Definition, count, a) if allocation != nil do return .Allocation value.definitions, allocation = make([]provider.Tool_Definition, count, a) if allocation != nil do return .Allocation for i in 0.. 0 { destroy_envelope(value.items[value.head]); value.head = (value.head + 1) % MAILBOX_ITEMS; value.count -= 1 } a := budget_allocator(&value.snapshot_budget) destroy_request(&value.request, a) conversation.destroy_identity(&value.identity, a) conversation.destroy_selection(&value.selection, a) content := conversation.Content(value.call); conversation.destroy_content(&content, a) delete(value.definition.name, a); delete(value.definition.description, a); delete(value.definition.input_schema_json, a) delete(value.tool_context.workspace, a) delete(value.tool_context.native.id, a); delete(value.tool_context.native.description, a) delete(value.tool_context.process.id, a); delete(value.tool_context.process.description, a) conversation.destroy(&value.session) delete(value.checkpoint.session_id, a) destroy_event(&value.terminal, budget_allocator(&value.output_budget)) tool.destroy_result(&value.result, budget_allocator(&value.output_budget)) sessionstore.destroy_error(&value.store_error, budget_allocator(&value.output_budget)) free(value, value.allocator) } // Does NOT destroy Runtime or borrowed service data. close first when initialized. destroy_executor :: proc(value: ^Executor) { assert(value.active == nil && value.pending == nil && !value.entered) if value.runtime != nil && value.runtime.executor == value do value.runtime.executor = nil a := budget_allocator(&value.config_budget) delete(value.config.instructions, a) delete(value.config.native.id, a); delete(value.config.native.description, a) delete(value.config.process.id, a); delete(value.config.process.description, a) for entry in value.entries { delete(entry.name, a); delete(entry.description, a); delete(entry.input_schema_json, a) } delete(value.entries, a); delete(value.definitions, a) value^ = {} } make_job :: proc(value: ^Executor, action: agent.Action) -> (out_job: ^Job, error: conversation.Error) { job: ^Job allocation: mem.Allocator_Error job, allocation = new(Job, value.allocator) if allocation != nil do return nil, .Allocation job.allocator = value.allocator job.model = value.active_model job.capabilities = value.runtime.agent.active_capabilities job.enforce_capabilities = value.runtime.agent.enforce_capabilities job.store = value.runtime.services.store job.snapshot_budget = {backing = value.allocator, limit = SNAPSHOT_BYTES} job.output_budget = {backing = value.allocator, limit = OUTPUT_ALLOCATION_BYTES} a := budget_allocator(&job.snapshot_budget) committed := false defer { if !committed do destroy_job(job) } switch item in action { case agent.Request_Model: job.kind = .Model job.request, allocation = clone_request(item.request, a) case agent.Execute_Tool: job.kind = .Tool job.identity, allocation = conversation.clone_identity(item.identity, a) if allocation != nil do return nil, .Allocation job.selection, allocation = conversation.clone_selection(item.selection, a) if allocation != nil do return nil, .Allocation content, err := conversation.clone_content(item.call, a) if err != nil do return nil, .Allocation job.call = content.(conversation.Tool_Call) now := value.runtime.services.clock.monotonic(value.runtime.services.clock.data) if now < 0 || now > max(time.Duration) - value.config.tool_timeout do return nil, .Invalid_Time job.tool_context = {native = value.config.native, process = value.config.process, allocator = budget_allocator(&job.output_budget), identity = job.identity, selection = job.selection, max_output_bytes = TOOL_OUTPUT_BYTES, deadline = now + value.config.tool_timeout, clock_data = value.runtime.services.clock.data, monotonic = value.runtime.services.clock.monotonic, progress = {job, tool_progress}, cancel_data = job, is_cancelled = job_cancelled} job.tool_context.native.id = ""; job.tool_context.native.description = "" job.tool_context.process.id = ""; job.tool_context.process.description = "" job.tool_context.native.id, allocation = strings.clone(value.config.native.id, a) if allocation != nil do return nil, .Allocation job.tool_context.native.description, allocation = strings.clone(value.config.native.description, a) if allocation != nil do return nil, .Allocation job.tool_context.process.id, allocation = strings.clone(value.config.process.id, a) if allocation != nil do return nil, .Allocation job.tool_context.process.description, allocation = strings.clone(value.config.process.description, a) if allocation != nil do return nil, .Allocation job.tool_context.workspace, allocation = strings.clone(value.runtime.conversation.workspace, a) if allocation != nil do return nil, .Allocation for entry in value.entries { if entry.name != item.call.name do continue job.definition.data = entry.data; job.definition.execute = entry.execute job.definition.name, allocation = strings.clone(entry.name, a) if allocation != nil do return nil, .Allocation job.definition.description, allocation = strings.clone(entry.description, a) if allocation != nil do return nil, .Allocation job.definition.input_schema_json, allocation = strings.clone(entry.input_schema_json, a) break } case agent.Checkpoint: job.kind = .Save job.checkpoint = item; job.checkpoint.session_id = "" job.checkpoint.session_id, allocation = strings.clone(item.session_id, a) if allocation != nil do return nil, .Allocation job.session, allocation = conversation.clone_session(&value.runtime.conversation, a) if allocation == nil && (job.session.id != item.session_id || job.session.revision != item.revision) do return nil, .Invalid_State case agent.Cancel_Model, agent.Cancel_Tools: return nil, .Invalid_State case: return nil, .Invalid_State } if allocation != nil do return nil, .Allocation committed = true return job, .None } start_job :: proc(value: ^Executor, job: ^Job) { assert(value.active == nil) value.active = job // Thread struct creation and callback context explicitly use the worker-safe allocator. context.allocator = value.allocator job.thread = thread.create(worker) if job.thread == nil { job.setup_failed = true; job.released = true; return } job.thread.data = job thread.start(job.thread) } cancel_job :: proc(job: ^Job) { if job == nil do return sync.mutex_lock(&job.mutex) job.cancelled = true sync.cond_broadcast(&job.changed) sync.mutex_unlock(&job.mutex) } job_cancelled :: proc(data: rawptr) -> bool { job := (^Job)(data) sync.mutex_lock(&job.mutex) defer sync.mutex_unlock(&job.mutex) return job.cancelled || job.protocol_failed } // Takes ownership on every path. Producer holds at most one extra bounded item. publish :: proc(job: ^Job, message: ^Envelope) { sync.mutex_lock(&job.mutex) defer sync.mutex_unlock(&job.mutex) for !job.cancelled && !job.protocol_failed && (job.count == MAILBOX_ITEMS || message.budget.spent > MAILBOX_BYTES - job.bytes) { sync.cond_wait(&job.changed, &job.mutex) } if job.cancelled || job.protocol_failed { destroy_envelope(message); return } job.items[(job.head + job.count) % MAILBOX_ITEMS] = message job.count += 1; job.bytes += message.budget.spent sync.cond_broadcast(&job.changed) } provider_emit :: proc(data: rawptr, identity: conversation.Request_Identity, event: provider.Event) { job := (^Job)(data) // Foreign callback data is still borrowed: reject before allocating or changing // this job's protocol/cancellation state, including after its terminal callback. if !conversation.same_request(identity, job.request.identity) do return if job.enforce_capabilities { #partial switch _ in event { case provider.Tool_Calls: if !job.capabilities.tools { cancel_protocol(job); return } case provider.Reasoning_Start, provider.Reasoning_Delta, provider.Reasoning_End: if !job.capabilities.reasoning { cancel_protocol(job); return } case: } } metadata := false if conversation.same_request(identity, job.request.identity) { if usage, ok := event.(provider.Usage); ok { metadata = true if !retain_usage(job, usage) { cancel_protocol(job); return } } if model, ok := event.(provider.Served_Model); ok { metadata = true if !conversation.valid_text(model.id, conversation.MAX_IDENTIFIER_BYTES, true) { cancel_protocol(job); return } copy(job.served_model[:], transmute([]byte)model.id) job.served_model_count = len(model.id) } } terminal := false switch _ in event { case provider.Completed, provider.Failure, provider.Cancelled: terminal = true case provider.Text_Delta, provider.Reasoning_Start, provider.Reasoning_Delta, provider.Reasoning_End, provider.Tool_Calls, provider.Usage, provider.Served_Model, provider.Continuation: case: } if terminal { if !conversation.same_request(identity, job.request.identity) do return if job.terminal_seen { cancel_protocol(job); return } job.terminal_seen = true if failure, ok := event.(provider.Failure); ok && len(failure.message) > TOOL_OUTPUT_BYTES { cancel_protocol(job); return } owned, allocation := clone_event(event, budget_allocator(&job.output_budget)) if allocation != nil { cancel_protocol(job); return } job.terminal = owned return } if job.terminal_seen && !metadata { cancel_protocol(job); return } // Fixed final metadata survives cancellation/backpressure and terminal-before-return. if metadata && (job.terminal_seen || job_cancelled(job)) do return message, allocation := new(Envelope, job.allocator) if allocation != nil { cancel_protocol(job); return } message.budget = {backing = job.allocator, limit = MAILBOX_BYTES} a := budget_allocator(&message.budget) message.identity, allocation = conversation.clone_identity(identity, a) if allocation == nil do message.event, allocation = clone_event(event, a) if allocation != nil { destroy_envelope(message); cancel_protocol(job); return } publish(job, message) } retain_usage :: proc(job: ^Job, usage: provider.Usage) -> bool { if usage.sequence == 0 || (usage.mode != .Snapshot && usage.mode != .Delta) do return false if usage.sequence <= job.final_usage.sequence do return true for counter in ([?]conversation.Counter{usage.tokens.input, usage.tokens.output, usage.tokens.cached_input, usage.tokens.reasoning_output, usage.context_usage.used, usage.context_usage.limit}) { if !counter.known && counter.value != 0 do return false } merged := job.final_usage ok: bool merged.tokens.input, ok = conversation.update_counter(merged.tokens.input, usage.tokens.input, usage.mode) if !ok do return false merged.tokens.output, ok = conversation.update_counter(merged.tokens.output, usage.tokens.output, usage.mode) if !ok do return false merged.tokens.cached_input, ok = conversation.update_counter(merged.tokens.cached_input, usage.tokens.cached_input, usage.mode) if !ok do return false merged.tokens.reasoning_output, ok = conversation.update_counter(merged.tokens.reasoning_output, usage.tokens.reasoning_output, usage.mode) if !ok do return false if usage.context_usage.used.known do merged.context_usage.used = usage.context_usage.used if usage.context_usage.limit.known do merged.context_usage.limit = usage.context_usage.limit merged.sequence = usage.sequence merged.mode = .Snapshot job.final_usage = merged return true } cancel_protocol :: proc(job: ^Job) { sync.mutex_lock(&job.mutex) job.protocol_failed = true sync.cond_broadcast(&job.changed) sync.mutex_unlock(&job.mutex) } tool_progress :: proc(data: rawptr, identity: conversation.Request_Identity, call_id, text: string) { job := (^Job)(data) if !conversation.same_request(identity, job.identity) || call_id != job.call.id do return if len(text) > TOOL_OUTPUT_BYTES do return // Progress is optional; never truncate a result. message, allocation := new(Envelope, job.allocator) if allocation != nil do return message.budget = {backing = job.allocator, limit = MAILBOX_BYTES} message.is_progress = true a := budget_allocator(&message.budget) message.identity, allocation = conversation.clone_identity(identity, a) if allocation == nil do message.call_id, allocation = strings.clone(call_id, a) if allocation == nil do message.progress, allocation = strings.clone(text, a) if allocation != nil { destroy_envelope(message); return } publish(job, message) } worker :: proc(t: ^thread.Thread) { job := (^Job)(t.data) context.allocator = job.allocator // Default thread-local temporary allocator is initialized/destroyed by core:thread. switch job.kind { case .Model: job.model.run(job.model.data, job.request, {job, provider_emit}, {job, job_cancelled}) case .Tool: if job.definition.execute == nil { job.result = {status = .Invalid_Arguments, execution = {state = .Not_Started}} } else { job.result = job.definition.execute(job.definition.data, job.tool_context, job.call) if job.output_budget.failed { job.result.status = .Failed; job.setup_failed = true } if len(job.result.text) > TOOL_OUTPUT_BYTES { execution := job.result.execution tool.destroy_result(&job.result, job.tool_context.allocator) job.result = {status = .Failed, execution = execution}; job.setup_failed = true } } case .Save: if job.checkpoint.policy == .Durable { job.store_error = job.store.save(job.store.data, {&job.session, job.checkpoint.revision}, budget_allocator(&job.output_budget)) if job.output_budget.failed || len(job.store_error.message) > TOOL_OUTPUT_BYTES || (job.store_error.kind == .None && job.store_error.message != "") { kind := job.store_error.kind sessionstore.destroy_error(&job.store_error, budget_allocator(&job.output_budget)) // WP9 post-rename uncertainty must not become a misleading pre-write // allocation/limit error merely because its diagnostic was refused. job.store_error.kind = .Durability if kind == .Durability else .Limit } } } sync.mutex_lock(&job.mutex) job.released = true sync.cond_broadcast(&job.changed) sync.mutex_unlock(&job.mutex) } save_failure :: proc(kind: sessionstore.Error_Kind) -> agent.Checkpoint_Failure { #partial switch kind { case .None: return .None case .Locked: return .Locked case .Revision_Conflict: return .Revision_Conflict case .Limit: return .Limit case .Invalid_Data, .Unsupported_Version: return .Invalid_Data case: return .IO } } terminal_input :: proc(job: ^Job) -> agent.Input { switch job.kind { case .Model: event := job.terminal if job.setup_failed || job.protocol_failed || !job.terminal_seen do event = provider.Failure{kind = .Malformed_Stream} return agent.Model_Event{job.request.identity, event} case .Tool: return agent.Tool_Completed{job.identity, job.call.id, job.result, job.setup_failed} case .Save: failure := save_failure(job.store_error.kind) if job.setup_failed do failure = .IO return agent.Checkpoint_Completed{checkpoint = job.checkpoint, succeeded = failure == .None, failure = failure, message = job.store_error.message} } return {} } // Immediate owner-thread input. Sink borrows events; recursive send/poll is refused. send :: proc(value: ^Executor, input: agent.Input) -> conversation.Error { if value.runtime == nil || value.owner != sync.current_thread_id() || value.entered do return .Invalid_State if value.stopping { if _, submit := input.(agent.Submit); submit do return .Invalid_State if _, selection := input.(agent.Set_Selection); selection do return .Invalid_State } switch _ in input { case agent.Submit, agent.Set_Selection, agent.Suspend, agent.Cancel, agent.Retry_Save: case agent.Model_Event, agent.Tool_Completed, agent.Tool_Progressed, agent.Checkpoint_Completed: return .Invalid_State case: return .Invalid_State } // WP9 restores unavailable selections without substituting a provider. An // already-attached executor must refuse admission before mutating draft/queue, // not invoke a nil adapter or create a new request against an old provider. if _, submit := input.(agent.Submit); submit && value.runtime.services.model.run == nil do return .Invalid_Selection value.entered = true defer { value.entered = false } return apply(value, input) } apply :: proc(value: ^Executor, initial: agent.Input) -> conversation.Error { input := initial first_error := conversation.Error.None for { out := reducer_step(value.runtime, input, value.config.instructions, value.definitions, value.config.projection_limits) if first_error == .None do first_error = out.error value.last_error = first_error for event in out.events[:out.event_count] { if _, started := event.(agent.Turn_Started); started do value.active_model = value.runtime.services.model if value.sink.emit != nil do value.sink.emit(value.sink.data, event) } failed := false next: agent.Input for action in out.actions[:out.action_count] { switch item in action { case agent.Cancel_Model: if value.active != nil && value.active.kind == .Model && conversation.same_request(item.identity, value.active.request.identity) do cancel_job(value.active) case agent.Cancel_Tools: if value.active != nil && value.active.kind == .Tool && conversation.same_request(item.identity, value.active.identity) && item.call_id == value.active.call.id do cancel_job(value.active) case agent.Request_Model, agent.Execute_Tool, agent.Checkpoint: // A new gate supersedes any not-started snapshot before allocating its replacement. if _, save := action.(agent.Checkpoint); save && value.pending != nil { destroy_job(value.pending); value.pending = nil } job, error := make_job(value, action) if error != .None { value.last_error = error if first_error == .None do first_error = error failed = true switch original in action { case agent.Request_Model: next = agent.Model_Event{original.request.identity, provider.Failure{kind = .Invalid_Request}} case agent.Execute_Tool: next = agent.Tool_Completed{identity = original.identity, call_id = original.call.id, result = {status = .Failed}, infrastructure_failure = true} case agent.Checkpoint: next = agent.Checkpoint_Completed{checkpoint = original, failure = .Limit} case agent.Cancel_Model, agent.Cancel_Tools: case: } } else if value.active == nil { start_job(value, job) } else { // Only superseded save gates can occur while a worker is active. assert(job.kind == .Save && value.active.kind == .Save) value.pending = job } case: } } if !failed { value.last_error = first_error; return first_error } input = next // No callback reentry; borrowed failed-action key consumed before another step. } } // Drains one ordered owned event or joins a released worker and applies its terminal. // wait=false is nonblocking. wait=true is for headless loops/shutdown, not UI input. poll :: proc(value: ^Executor, wait := false) -> bool { if value.runtime == nil || value.owner != sync.current_thread_id() || value.entered || value.active == nil do return false value.entered = true defer { value.entered = false } job := value.active sync.mutex_lock(&job.mutex) for wait && job.count == 0 && !job.released do sync.cond_wait(&job.changed, &job.mutex) if job.count > 0 { message := job.items[job.head]; job.items[job.head] = nil job.head = (job.head + 1) % MAILBOX_ITEMS; job.count -= 1; job.bytes -= message.budget.spent sync.cond_broadcast(&job.changed) sync.mutex_unlock(&job.mutex) input := agent.Input(agent.Model_Event{message.identity, message.event}) if message.is_progress do input = agent.Tool_Progressed{message.identity, message.call_id, message.progress} apply(value, input) destroy_envelope(message) // Also on stale/duplicate/rejected input. return true } released := job.released sync.mutex_unlock(&job.mutex) if !released do return false if !wait && job.thread != nil && !thread.is_done(job.thread) do return false if job.thread != nil { thread.join(job.thread); thread.destroy(job.thread); job.thread = nil } value.active = nil input := terminal_input(job) if job.kind == .Model { if job.final_usage.sequence != 0 do apply(value, agent.Model_Event{job.request.identity, job.final_usage}) if job.served_model_count > 0 do apply(value, agent.Model_Event{job.request.identity, provider.Served_Model{transmute(string)job.served_model[:job.served_model_count]}}) } if job.kind == .Save && job.checkpoint.reason == .Shutdown { completion := input.(agent.Checkpoint_Completed) value.shutdown_saved = completion.succeeded value.shutdown_failed = !completion.succeeded if completion.succeeded do value.runtime.agent.durable_revision = job.checkpoint.revision else { // Save-only failure must block recovery, but cannot revise a previously // durable completed turn. Clear inactive IDs before reducer Retry_Save. state := &value.runtime.agent state.phase = .Durability_Blocked state.turn_id = 0; state.request_id = 0; state.identity = {}; state.checkpoint = {} if value.sink.emit != nil do value.sink.emit(value.sink.data, agent.Durability_Warning{value.runtime.conversation.revision}) } } else do apply(value, input) if value.stopping && value.runtime.agent.phase == .Idle && value.runtime.agent.durable_revision == value.runtime.conversation.revision do value.shutdown_failed = false destroy_job(job) if value.active == nil && value.pending != nil { pending := value.pending; value.pending = nil; start_job(value, pending) } return true } // Stop admission, suspend dequeue, commit cancellation, drain/join, then save latest // idle revision if needed. No automatic retry of failed saves or effects. Cooperative // adapters must return after cancellation; a hung backend is never forcibly freed. close :: proc(value: ^Executor) -> bool { if value.runtime == nil do return true if value.owner != sync.current_thread_id() || value.entered do return false value.stopping = true send(value, agent.Suspend{true}) send(value, agent.Cancel{}) count := agent.clear_queue(&value.runtime.agent.pending) if count > 0 && value.sink.emit != nil { value.entered = true; value.sink.emit(value.sink.data, agent.Queue_Discarded{count}); value.entered = false } for value.active != nil do poll(value, true) if value.runtime.agent.phase != .Idle do return false if value.runtime.agent.durable_revision < value.runtime.conversation.revision && !value.shutdown_saved && !value.shutdown_failed { services := value.runtime.services sync.mutex_lock(services.identity_mutex) id, ok := agent.issue(services.identities) sync.mutex_unlock(services.identity_mutex) if !ok do return false key := agent.Checkpoint{id = id, session_id = value.runtime.conversation.id, revision = value.runtime.conversation.revision, policy = services.checkpoint_policy, reason = .Shutdown} job, error := make_job(value, key) if error != .None do return false start_job(value, job) for value.active != nil do poll(value, true) } return !value.shutdown_failed && value.runtime.agent.durable_revision == value.runtime.conversation.revision }