Skip to content

Control-plane reference

Expose authenticated mission, worker, artifact, and migration APIs.

(c) Mike Casale 2026. Licensed under the MIT License.

ErrorDetail

Bases: _WireModel

Machine-readable API failure.

Source code in agent_k/api.py
77
78
79
80
81
82
83
84
class ErrorDetail(_WireModel):
    """Machine-readable API failure."""

    code: str
    message: str
    retryable: bool = False
    category: str | None = None
    details: JsonObject | None = None

ErrorResponse

Bases: _WireModel

Stable error envelope returned by every JSON endpoint.

Source code in agent_k/api.py
87
88
89
90
91
class ErrorResponse(_WireModel):
    """Stable error envelope returned by every JSON endpoint."""

    error: ErrorDetail
    request_id: str

ApiError

Bases: Exception

HTTP-safe application error with a stable wire code.

Source code in agent_k/api.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
class ApiError(Exception):
    """HTTP-safe application error with a stable wire code."""

    def __init__(
        self,
        status_code: int,
        code: str,
        message: str,
        *,
        retryable: bool = False,
        details: JsonObject | None = None,
    ) -> None:
        self.status_code = status_code
        self.code = code
        self.message = message
        self.retryable = retryable
        self.details = details
        super().__init__(message)

UserIdentity

Bases: _WireModel

Verified identity forwarded by the Auth.js frontend.

Source code in agent_k/api.py
114
115
116
117
118
class UserIdentity(_WireModel):
    """Verified identity forwarded by the Auth.js frontend."""

    user_id: str = Field(min_length=1, max_length=200)
    token_id: str = Field(min_length=1, max_length=200)

WorkerIdentity

Bases: _WireModel

Verified internal worker identity.

Source code in agent_k/api.py
121
122
123
124
class WorkerIdentity(_WireModel):
    """Verified internal worker identity."""

    worker_id: str = Field(min_length=1, max_length=200)

GatewayClaims

Bases: _WireModel

Signed short-lived frontend identity claims.

Source code in agent_k/api.py
127
128
129
130
131
132
133
134
135
class GatewayClaims(_WireModel):
    """Signed short-lived frontend identity claims."""

    sub: str = Field(min_length=1, max_length=200)
    iss: str
    aud: str
    iat: int
    exp: int
    jti: str = Field(min_length=1, max_length=200)

GatewayVerifier dataclass

Verify HMAC-signed frontend identity tokens with key rotation.

Source code in agent_k/api.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
@dataclass(frozen=True, slots=True)
class GatewayVerifier:
    """Verify HMAC-signed frontend identity tokens with key rotation."""

    secrets: tuple[SecretStr, ...]
    issuer: str
    audience: str
    max_ttl_seconds: int = 60
    clock_skew_seconds: int = 10

    def verify(self, token: str) -> UserIdentity:
        """Verify one compact HS256 token and return its user identity."""
        try:
            encoded_header, encoded_claims, encoded_signature = token.split(".")
        except ValueError as exc:
            raise ApiError(401, "invalid_identity", "Invalid identity token") from exc

        header = _decode_json_segment(encoded_header)
        if header != {"alg": "HS256", "typ": "JWT"}:
            raise ApiError(401, "invalid_identity", "Invalid identity token")

        signing_input = f"{encoded_header}.{encoded_claims}".encode()
        signature = _decode_segment(encoded_signature)
        valid_signature = any(
            hmac.compare_digest(
                signature,
                hmac.digest(secret.get_secret_value().encode(), signing_input, "sha256"),
            )
            for secret in self.secrets
        )
        if not valid_signature:
            raise ApiError(401, "invalid_identity", "Invalid identity token")

        try:
            claims = GatewayClaims.model_validate(_decode_json_segment(encoded_claims))
        except ValueError as exc:
            raise ApiError(401, "invalid_identity", "Invalid identity token") from exc

        now = int(time.time())
        if claims.iss != self.issuer or claims.aud != self.audience:
            raise ApiError(401, "invalid_identity", "Invalid identity token")
        if claims.iat > now + self.clock_skew_seconds:
            raise ApiError(401, "invalid_identity", "Identity token is not active")
        if claims.exp <= now - self.clock_skew_seconds:
            raise ApiError(401, "expired_identity", "Identity token has expired")
        if claims.exp - claims.iat > self.max_ttl_seconds:
            raise ApiError(401, "invalid_identity", "Identity token lifetime is too long")
        return UserIdentity(user_id=claims.sub, token_id=claims.jti)

verify

verify(token: str) -> UserIdentity

Verify one compact HS256 token and return its user identity.

Source code in agent_k/api.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def verify(self, token: str) -> UserIdentity:
    """Verify one compact HS256 token and return its user identity."""
    try:
        encoded_header, encoded_claims, encoded_signature = token.split(".")
    except ValueError as exc:
        raise ApiError(401, "invalid_identity", "Invalid identity token") from exc

    header = _decode_json_segment(encoded_header)
    if header != {"alg": "HS256", "typ": "JWT"}:
        raise ApiError(401, "invalid_identity", "Invalid identity token")

    signing_input = f"{encoded_header}.{encoded_claims}".encode()
    signature = _decode_segment(encoded_signature)
    valid_signature = any(
        hmac.compare_digest(
            signature,
            hmac.digest(secret.get_secret_value().encode(), signing_input, "sha256"),
        )
        for secret in self.secrets
    )
    if not valid_signature:
        raise ApiError(401, "invalid_identity", "Invalid identity token")

    try:
        claims = GatewayClaims.model_validate(_decode_json_segment(encoded_claims))
    except ValueError as exc:
        raise ApiError(401, "invalid_identity", "Invalid identity token") from exc

    now = int(time.time())
    if claims.iss != self.issuer or claims.aud != self.audience:
        raise ApiError(401, "invalid_identity", "Invalid identity token")
    if claims.iat > now + self.clock_skew_seconds:
        raise ApiError(401, "invalid_identity", "Identity token is not active")
    if claims.exp <= now - self.clock_skew_seconds:
        raise ApiError(401, "expired_identity", "Identity token has expired")
    if claims.exp - claims.iat > self.max_ttl_seconds:
        raise ApiError(401, "invalid_identity", "Identity token lifetime is too long")
    return UserIdentity(user_id=claims.sub, token_id=claims.jti)

WorkerVerifier dataclass

Verify rotatable opaque internal worker bearer tokens.

Source code in agent_k/api.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
@dataclass(frozen=True, slots=True)
class WorkerVerifier:
    """Verify rotatable opaque internal worker bearer tokens."""

    tokens: tuple[SecretStr, ...]

    def verify(self, token: str, worker_id: str) -> WorkerIdentity:
        """Return the worker identity when a configured token matches."""
        presented = token.encode()
        if not any(
            hmac.compare_digest(presented, candidate.get_secret_value().encode())
            for candidate in self.tokens
        ):
            raise ApiError(401, "invalid_worker_token", "Invalid worker token")
        return WorkerIdentity(worker_id=worker_id)

verify

verify(token: str, worker_id: str) -> WorkerIdentity

Return the worker identity when a configured token matches.

Source code in agent_k/api.py
194
195
196
197
198
199
200
201
202
def verify(self, token: str, worker_id: str) -> WorkerIdentity:
    """Return the worker identity when a configured token matches."""
    presented = token.encode()
    if not any(
        hmac.compare_digest(presented, candidate.get_secret_value().encode())
        for candidate in self.tokens
    ):
        raise ApiError(401, "invalid_worker_token", "Invalid worker token")
    return WorkerIdentity(worker_id=worker_id)

MissionStartRequest

Bases: _WireModel

Create a durable mission job.

Source code in agent_k/api.py
205
206
207
208
209
210
211
212
213
class MissionStartRequest(_WireModel):
    """Create a durable mission job."""

    schema_version: str = "1.0.0"
    criteria: MissionCriteriaInput
    evolution_models: list[str] | None = None
    user_prompt: str | None = Field(default=None, max_length=20_000)
    competition_id: str | None = Field(default=None, min_length=1, max_length=200)
    competition_url: str | None = Field(default=None, min_length=10, max_length=2_000)

MissionStartResponse

Bases: _WireModel

Identity and initial status of a newly queued mission.

Source code in agent_k/api.py
216
217
218
219
220
class MissionStartResponse(_WireModel):
    """Identity and initial status of a newly queued mission."""

    mission_id: str
    status: str = "queued"

MissionStatusResponse

Bases: _WireModel

Current durable mission status.

Source code in agent_k/api.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
class MissionStatusResponse(_WireModel):
    """Current durable mission status."""

    mission_id: str
    status: str
    current_phase: str | None = None
    progress: float = Field(default=0.0, ge=0.0, le=100.0)
    competition_id: str | None = None
    error_message: str | None = None
    latest_sequence: int = Field(default=0, ge=0)
    iteration: int | None = Field(default=None, ge=0)
    evolution_iterations: int | None = Field(default=None, ge=0)
    model_family: ModelFamily | None = None
    model_size: ModelSize | None = None
    created_at: datetime | None = None
    updated_at: datetime | None = None

MissionControlResponse

Bases: _WireModel

Accepted user control request.

Source code in agent_k/api.py
241
242
243
244
245
246
class MissionControlResponse(_WireModel):
    """Accepted user control request."""

    mission_id: str
    status: str
    action: MissionControlAction

CompetitionSearchRequest

Bases: _WireModel

Search filters for the real competition platform.

Source code in agent_k/api.py
249
250
251
252
253
254
255
256
class CompetitionSearchRequest(_WireModel):
    """Search filters for the real competition platform."""

    paid_only: bool = False
    domains: list[str] = Field(default_factory=list)
    competition_types: list[str] = Field(default_factory=list)
    min_prize: int | None = Field(default=None, ge=0)
    min_days_remaining: int = Field(default=7, ge=1)

CompetitionFetchRequest

Bases: _WireModel

Fetch one competition by its platform URL.

Source code in agent_k/api.py
259
260
261
262
class CompetitionFetchRequest(_WireModel):
    """Fetch one competition by its platform URL."""

    url: str = Field(min_length=10, max_length=2_000)

ControlState

Bases: _WireModel

Control action visible to a leased worker.

Source code in agent_k/api.py
265
266
267
268
269
270
class ControlState(_WireModel):
    """Control action visible to a leased worker."""

    action: ControlAction = "continue"
    reason: str | None = None
    requested_at: datetime | None = None

JobCommand

Bases: _WireModel

Mission command assigned to a worker.

Source code in agent_k/api.py
273
274
275
276
277
278
279
class JobCommand(_WireModel):
    """Mission command assigned to a worker."""

    type: Literal["start", "resume"]
    competition_id: str | None = None
    criteria: JsonObject
    checkpoint_id: str | None = None

JobWorkspace

Bases: _WireModel

Artifact namespace reserved for one job attempt.

Source code in agent_k/api.py
282
283
284
285
class JobWorkspace(_WireModel):
    """Artifact namespace reserved for one job attempt."""

    artifact_prefix: str

ClaimedJob

Bases: _WireModel

Fenced lease and mission command returned by a claim.

Source code in agent_k/api.py
288
289
290
291
292
293
294
295
296
297
298
299
class ClaimedJob(_WireModel):
    """Fenced lease and mission command returned by a claim."""

    schema_version: str = "1.0.0"
    job_id: str
    mission_id: str
    attempt: int = Field(ge=1)
    lease_id: str
    lease_expires_at: datetime
    command: JobCommand
    workspace: JobWorkspace
    event_sequence: int = Field(default=0, ge=0)

ClaimJobsRequest

Bases: _WireModel

Worker request for available jobs.

Source code in agent_k/api.py
302
303
304
305
306
307
308
class ClaimJobsRequest(_WireModel):
    """Worker request for available jobs."""

    worker_id: str = Field(min_length=1, max_length=200)
    capabilities: list[str] = Field(default_factory=list)
    lease_seconds: int = Field(default=60, ge=15, le=3_600)
    max_jobs: int = Field(default=1, ge=1, le=16)

ClaimJobsResponse

Bases: _WireModel

Atomically claimed jobs and server clock.

Source code in agent_k/api.py
311
312
313
314
315
class ClaimJobsResponse(_WireModel):
    """Atomically claimed jobs and server clock."""

    jobs: list[ClaimedJob] = Field(default_factory=list)
    server_time: datetime

HeartbeatRequest

Bases: _WireModel

Renew a fenced job lease and report progress.

Source code in agent_k/api.py
318
319
320
321
322
323
324
325
class HeartbeatRequest(_WireModel):
    """Renew a fenced job lease and report progress."""

    worker_id: str
    lease_id: str
    progress: float | None = Field(default=None, ge=0.0, le=100.0)
    current_phase: str | None = None
    current_task_id: str | None = None

HeartbeatResponse

Bases: _WireModel

Renewed lease and current control action.

Source code in agent_k/api.py
328
329
330
331
332
333
334
335
class HeartbeatResponse(_WireModel):
    """Renewed lease and current control action."""

    job_id: str
    lease_id: str
    lease_expires_at: datetime
    control: ControlState
    server_time: datetime

AppendEventsRequest

Bases: _WireModel

Append one contiguous ordered batch of mission events.

Source code in agent_k/api.py
338
339
340
341
342
343
class AppendEventsRequest(_WireModel):
    """Append one contiguous ordered batch of mission events."""

    worker_id: str
    lease_id: str
    events: list[WorkerEvent] = Field(min_length=1, max_length=256)

AppendEventsResponse

Bases: _WireModel

Event append acknowledgement.

Source code in agent_k/api.py
346
347
348
349
350
351
class AppendEventsResponse(_WireModel):
    """Event append acknowledgement."""

    accepted_through: int = Field(ge=0)
    duplicate_sequences: list[int] = Field(default_factory=list)
    control: ControlState

SnapshotPayload

Bases: _WireModel

Versioned mission snapshot supplied by a worker.

Source code in agent_k/api.py
354
355
356
357
358
359
360
361
class SnapshotPayload(_WireModel):
    """Versioned mission snapshot supplied by a worker."""

    schema_version: str
    sequence: int = Field(ge=0)
    created_at: datetime
    content_type: Literal["application/json"] = "application/json"
    payload: JsonObject

SaveSnapshotRequest

Bases: _WireModel

Save an idempotent mission snapshot.

Source code in agent_k/api.py
364
365
366
367
368
369
class SaveSnapshotRequest(_WireModel):
    """Save an idempotent mission snapshot."""

    worker_id: str
    lease_id: str
    snapshot: SnapshotPayload

SaveSnapshotResponse

Bases: _WireModel

Stored snapshot identity.

Source code in agent_k/api.py
372
373
374
375
376
377
class SaveSnapshotResponse(_WireModel):
    """Stored snapshot identity."""

    snapshot_id: str
    sequence: int = Field(ge=0)
    created_at: datetime

ArtifactReference

Bases: _WireModel

Artifact attached to a terminal mission result.

Source code in agent_k/api.py
380
381
382
383
384
class ArtifactReference(_WireModel):
    """Artifact attached to a terminal mission result."""

    artifact_id: str
    role: str

MissionSnapshotResponse

Bases: _WireModel

Durable resume snapshot and its externally stored artifacts.

Source code in agent_k/api.py
387
388
389
390
391
392
393
394
395
396
397
398
class MissionSnapshotResponse(_WireModel):
    """Durable resume snapshot and its externally stored artifacts."""

    snapshot_id: str
    job_id: str
    mission_id: str
    schema_version: str
    sequence: int = Field(ge=0)
    created_at: datetime
    content_type: Literal["application/json"] = "application/json"
    payload: JsonObject
    artifacts: list[ArtifactReference] = Field(default_factory=list)

MissionResultPayload

Bases: _WireModel

Successful worker result for a mission.

Source code in agent_k/api.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
class MissionResultPayload(_WireModel):
    """Successful worker result for a mission."""

    schema_version: str
    success: Literal[True]
    mission_id: str
    competition_id: str | None = None
    final_rank: int | None = Field(default=None, ge=1)
    final_score: float | None = None
    total_submissions: int = Field(ge=0)
    evolution_generations: int = Field(ge=0)
    evolution_iterations: int = Field(ge=0)
    duration_ms: int = Field(ge=0)
    phases_completed: list[str]
    final_event_sequence: int = Field(default=0, ge=0)
    artifacts: list[ArtifactReference] = Field(default_factory=list)

CompleteJobRequest

Bases: _WireModel

Commit a terminal successful job result.

Source code in agent_k/api.py
419
420
421
422
423
424
425
426
427
class CompleteJobRequest(_WireModel):
    """Commit a terminal successful job result."""

    worker_id: str
    lease_id: str
    idempotency_key: str = Field(min_length=16, max_length=200)
    result: MissionResultPayload
    final_event_sequence: int = Field(ge=0)
    artifacts: list[ArtifactReference] = Field(default_factory=list)

CompleteJobResponse

Bases: _WireModel

Committed successful job status.

Source code in agent_k/api.py
430
431
432
433
434
435
436
class CompleteJobResponse(_WireModel):
    """Committed successful job status."""

    job_id: str
    mission_id: str
    status: Literal["completed"]
    completed_at: datetime

WorkerFailure

Bases: _WireModel

Sanitized worker failure safe for persistence and operators.

Source code in agent_k/api.py
439
440
441
442
443
444
445
446
class WorkerFailure(_WireModel):
    """Sanitized worker failure safe for persistence and operators."""

    code: str
    message: str
    retryable: bool
    category: str | None = None
    details: JsonObject | None = None

FailJobRequest

Bases: _WireModel

Commit or retry a terminal worker failure.

Source code in agent_k/api.py
449
450
451
452
453
454
455
456
class FailJobRequest(_WireModel):
    """Commit or retry a terminal worker failure."""

    worker_id: str
    lease_id: str
    idempotency_key: str = Field(min_length=16, max_length=200)
    error: WorkerFailure
    final_event_sequence: int = Field(ge=0)

FailJobResponse

Bases: _WireModel

Failure disposition selected by the runtime store.

Source code in agent_k/api.py
459
460
461
462
463
464
465
466
467
class FailJobResponse(_WireModel):
    """Failure disposition selected by the runtime store."""

    job_id: str
    mission_id: str
    status: Literal["failed", "queued"]
    attempt: int = Field(ge=1)
    next_attempt_at: datetime | None = None
    failed_at: datetime | None = None

WorkerControlResponse

Bases: ControlState

Current worker control state and server clock.

Source code in agent_k/api.py
470
471
472
473
class WorkerControlResponse(ControlState):
    """Current worker control state and server clock."""

    server_time: datetime

ArtifactUploadRequest

Bases: _WireModel

Request a constrained signed artifact upload URL.

Source code in agent_k/api.py
476
477
478
479
480
481
482
483
484
485
class ArtifactUploadRequest(_WireModel):
    """Request a constrained signed artifact upload URL."""

    worker_id: str
    lease_id: str
    name: str = Field(min_length=1, max_length=500)
    content_type: str = Field(min_length=1, max_length=200)
    size_bytes: int = Field(ge=0)
    sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
    role: str = Field(min_length=1, max_length=100)

ArtifactDownloadRequest

Bases: _WireModel

Request a constrained signed artifact download URL.

Source code in agent_k/api.py
488
489
490
491
492
class ArtifactDownloadRequest(_WireModel):
    """Request a constrained signed artifact download URL."""

    worker_id: str
    lease_id: str

CompleteArtifactRequest

Bases: _WireModel

Finalize an uploaded artifact after server-side object verification.

Source code in agent_k/api.py
495
496
497
498
499
500
501
class CompleteArtifactRequest(_WireModel):
    """Finalize an uploaded artifact after server-side object verification."""

    worker_id: str
    lease_id: str
    sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
    size_bytes: int = Field(ge=0)

CompleteArtifactResponse

Bases: _WireModel

Verified immutable artifact status.

Source code in agent_k/api.py
504
505
506
507
508
509
class CompleteArtifactResponse(_WireModel):
    """Verified immutable artifact status."""

    artifact_id: str
    status: Literal["available"]
    verified_at: datetime

SignedArtifactResponse

Bases: _WireModel

Short-lived signed object storage operation.

Source code in agent_k/api.py
512
513
514
515
516
517
518
519
class SignedArtifactResponse(_WireModel):
    """Short-lived signed object storage operation."""

    artifact_id: str
    method: Literal["GET", "PUT"]
    url: str
    headers: dict[str, str] = Field(default_factory=dict)
    expires_at: datetime

MigrationSource

Bases: _WireModel

Source metadata for one legacy persistence upload.

Source code in agent_k/api.py
522
523
524
525
526
527
528
class MigrationSource(_WireModel):
    """Source metadata for one legacy persistence upload."""

    kind: Literal["mission-state", "experiment-db"]
    schema_version: str
    sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
    size_bytes: int = Field(ge=0)

CreateMigrationRequest

Bases: _WireModel

Create a signed upload for a legacy state migration.

Source code in agent_k/api.py
531
532
533
534
535
536
537
class CreateMigrationRequest(_WireModel):
    """Create a signed upload for a legacy state migration."""

    worker_id: str
    idempotency_key: str = Field(min_length=16, max_length=200)
    source: MigrationSource
    content_type: Literal["application/json", "application/x-sqlite3"]

SignedOperation

Bases: _WireModel

Signed storage operation embedded in another response.

Source code in agent_k/api.py
540
541
542
543
544
545
546
547
class SignedOperation(_WireModel):
    """Signed storage operation embedded in another response."""

    artifact_id: str
    method: Literal["PUT"]
    url: str
    headers: dict[str, str] = Field(default_factory=dict)
    expires_at: datetime

CreateMigrationResponse

Bases: _WireModel

Migration identity and its signed upload operation.

Source code in agent_k/api.py
550
551
552
553
554
555
class CreateMigrationResponse(_WireModel):
    """Migration identity and its signed upload operation."""

    migration_id: str
    upload: SignedOperation
    status: Literal["awaiting-upload"]

CompleteMigrationRequest

Bases: _WireModel

Confirm a completed legacy state upload.

Source code in agent_k/api.py
558
559
560
561
562
563
564
class CompleteMigrationRequest(_WireModel):
    """Confirm a completed legacy state upload."""

    worker_id: str
    idempotency_key: str = Field(min_length=16, max_length=200)
    sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
    size_bytes: int = Field(ge=0)

MigrationStatusResponse

Bases: _WireModel

Current migration processing status.

Source code in agent_k/api.py
567
568
569
570
571
572
573
574
575
576
577
578
579
class MigrationStatusResponse(_WireModel):
    """Current migration processing status."""

    migration_id: str
    status: Literal[
        "awaiting-upload",
        "queued",
        "running",
        "completed",
        "failed",
    ]
    counts: dict[str, int] | None = None
    error: ErrorDetail | None = None

ChatRequest

Bases: _WireModel

Vercel AI-style request forwarded by the authenticated frontend.

Source code in agent_k/api.py
582
583
584
585
586
587
class ChatRequest(_WireModel):
    """Vercel AI-style request forwarded by the authenticated frontend."""

    trigger: str | None = None
    id: str = Field(min_length=1, max_length=200)
    messages: list[JsonObject]

RuntimeStore

Bases: Protocol

Durable mission and worker operations required by the API.

Source code in agent_k/api.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
class RuntimeStore(Protocol):
    """Durable mission and worker operations required by the API."""

    async def create_mission(self, *, owner_id: str, request: JsonObject) -> JsonObject:
        """Create and enqueue one owned mission."""
        ...

    async def get_mission(self, mission_id: str) -> JsonObject | None:
        """Return one mission without applying an ownership check."""
        ...

    async def require_owner(self, mission_id: str, owner_id: str) -> JsonObject:
        """Return a mission only when the principal owns it."""
        ...

    async def request_control(
        self,
        mission_id: str,
        owner_id: str,
        action: MissionControlAction,
        reason: str | None,
    ) -> JsonObject:
        """Persist an owner-authorized mission control request."""
        ...

    async def list_events(
        self,
        mission_id: str,
        after_sequence: int,
        limit: int = DEFAULT_EVENT_BATCH_SIZE,
    ) -> list[JsonObject]:
        """Replay mission events after a durable global cursor."""
        ...

    async def list_best_results(self, owner_id: str, limit: int) -> list[JsonObject]:
        """Return ranked results restricted to one owner."""
        ...

    async def claim_jobs(self, request: JsonObject) -> JsonObject:
        """Atomically claim available jobs for a worker."""
        ...

    async def heartbeat(self, job_id: str, request: JsonObject) -> JsonObject:
        """Renew a fenced job lease."""
        ...

    async def append_events(self, job_id: str, request: JsonObject) -> JsonObject:
        """Append an ordered worker event batch."""
        ...

    async def save_snapshot(self, job_id: str, request: JsonObject) -> JsonObject:
        """Persist an idempotent mission snapshot."""
        ...

    async def get_snapshot(
        self,
        job_id: str,
        snapshot_id: str,
        worker_id: str,
        lease_id: str,
    ) -> JsonObject | None:
        """Load a snapshot through a current fenced lease."""
        ...

    async def complete_job(self, job_id: str, request: JsonObject) -> JsonObject:
        """Commit a successful fenced job."""
        ...

    async def fail_job(self, job_id: str, request: JsonObject) -> JsonObject:
        """Commit or retry a failed fenced job."""
        ...

    async def get_control(
        self,
        job_id: str,
        worker_id: str,
        lease_id: str,
    ) -> JsonObject:
        """Return control state through a current fenced lease."""
        ...

    async def get_migration(self, migration_id: str) -> JsonObject | None:
        """Return one durable migration record."""
        ...

create_mission async

create_mission(*, owner_id: str, request: JsonObject) -> JsonObject

Create and enqueue one owned mission.

Source code in agent_k/api.py
593
594
595
async def create_mission(self, *, owner_id: str, request: JsonObject) -> JsonObject:
    """Create and enqueue one owned mission."""
    ...

get_mission async

get_mission(mission_id: str) -> JsonObject | None

Return one mission without applying an ownership check.

Source code in agent_k/api.py
597
598
599
async def get_mission(self, mission_id: str) -> JsonObject | None:
    """Return one mission without applying an ownership check."""
    ...

require_owner async

require_owner(mission_id: str, owner_id: str) -> JsonObject

Return a mission only when the principal owns it.

Source code in agent_k/api.py
601
602
603
async def require_owner(self, mission_id: str, owner_id: str) -> JsonObject:
    """Return a mission only when the principal owns it."""
    ...

request_control async

request_control(mission_id: str, owner_id: str, action: MissionControlAction, reason: str | None) -> JsonObject

Persist an owner-authorized mission control request.

Source code in agent_k/api.py
605
606
607
608
609
610
611
612
613
async def request_control(
    self,
    mission_id: str,
    owner_id: str,
    action: MissionControlAction,
    reason: str | None,
) -> JsonObject:
    """Persist an owner-authorized mission control request."""
    ...

list_events async

list_events(mission_id: str, after_sequence: int, limit: int = DEFAULT_EVENT_BATCH_SIZE) -> list[JsonObject]

Replay mission events after a durable global cursor.

Source code in agent_k/api.py
615
616
617
618
619
620
621
622
async def list_events(
    self,
    mission_id: str,
    after_sequence: int,
    limit: int = DEFAULT_EVENT_BATCH_SIZE,
) -> list[JsonObject]:
    """Replay mission events after a durable global cursor."""
    ...

list_best_results async

list_best_results(owner_id: str, limit: int) -> list[JsonObject]

Return ranked results restricted to one owner.

Source code in agent_k/api.py
624
625
626
async def list_best_results(self, owner_id: str, limit: int) -> list[JsonObject]:
    """Return ranked results restricted to one owner."""
    ...

claim_jobs async

claim_jobs(request: JsonObject) -> JsonObject

Atomically claim available jobs for a worker.

Source code in agent_k/api.py
628
629
630
async def claim_jobs(self, request: JsonObject) -> JsonObject:
    """Atomically claim available jobs for a worker."""
    ...

heartbeat async

heartbeat(job_id: str, request: JsonObject) -> JsonObject

Renew a fenced job lease.

Source code in agent_k/api.py
632
633
634
async def heartbeat(self, job_id: str, request: JsonObject) -> JsonObject:
    """Renew a fenced job lease."""
    ...

append_events async

append_events(job_id: str, request: JsonObject) -> JsonObject

Append an ordered worker event batch.

Source code in agent_k/api.py
636
637
638
async def append_events(self, job_id: str, request: JsonObject) -> JsonObject:
    """Append an ordered worker event batch."""
    ...

save_snapshot async

save_snapshot(job_id: str, request: JsonObject) -> JsonObject

Persist an idempotent mission snapshot.

Source code in agent_k/api.py
640
641
642
async def save_snapshot(self, job_id: str, request: JsonObject) -> JsonObject:
    """Persist an idempotent mission snapshot."""
    ...

get_snapshot async

get_snapshot(job_id: str, snapshot_id: str, worker_id: str, lease_id: str) -> JsonObject | None

Load a snapshot through a current fenced lease.

Source code in agent_k/api.py
644
645
646
647
648
649
650
651
652
async def get_snapshot(
    self,
    job_id: str,
    snapshot_id: str,
    worker_id: str,
    lease_id: str,
) -> JsonObject | None:
    """Load a snapshot through a current fenced lease."""
    ...

complete_job async

complete_job(job_id: str, request: JsonObject) -> JsonObject

Commit a successful fenced job.

Source code in agent_k/api.py
654
655
656
async def complete_job(self, job_id: str, request: JsonObject) -> JsonObject:
    """Commit a successful fenced job."""
    ...

fail_job async

fail_job(job_id: str, request: JsonObject) -> JsonObject

Commit or retry a failed fenced job.

Source code in agent_k/api.py
658
659
660
async def fail_job(self, job_id: str, request: JsonObject) -> JsonObject:
    """Commit or retry a failed fenced job."""
    ...

get_control async

get_control(job_id: str, worker_id: str, lease_id: str) -> JsonObject

Return control state through a current fenced lease.

Source code in agent_k/api.py
662
663
664
665
666
667
668
669
async def get_control(
    self,
    job_id: str,
    worker_id: str,
    lease_id: str,
) -> JsonObject:
    """Return control state through a current fenced lease."""
    ...

get_migration async

get_migration(migration_id: str) -> JsonObject | None

Return one durable migration record.

Source code in agent_k/api.py
671
672
673
async def get_migration(self, migration_id: str) -> JsonObject | None:
    """Return one durable migration record."""
    ...

SignedArtifactStore

Bases: Protocol

Sign constrained S3 artifact transfers without proxying file bytes.

Source code in agent_k/api.py
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
class SignedArtifactStore(Protocol):
    """Sign constrained S3 artifact transfers without proxying file bytes."""

    async def sign_upload(self, job_id: str, request: JsonObject) -> JsonObject:
        """Reserve and sign a checksum-bound artifact upload."""
        ...

    async def sign_download(
        self,
        job_id: str,
        artifact_id: str,
        request: JsonObject,
    ) -> JsonObject:
        """Sign a fenced artifact download."""
        ...

    async def complete_upload(
        self,
        job_id: str,
        artifact_id: str,
        request: JsonObject,
    ) -> JsonObject:
        """Verify and finalize one artifact upload."""
        ...

    async def create_migration(self, request: JsonObject) -> JsonObject:
        """Create a signed legacy-state upload."""
        ...

    async def complete_migration(
        self,
        migration_id: str,
        request: JsonObject,
    ) -> JsonObject:
        """Verify and enqueue one legacy-state migration."""
        ...

sign_upload async

sign_upload(job_id: str, request: JsonObject) -> JsonObject

Reserve and sign a checksum-bound artifact upload.

Source code in agent_k/api.py
679
680
681
async def sign_upload(self, job_id: str, request: JsonObject) -> JsonObject:
    """Reserve and sign a checksum-bound artifact upload."""
    ...

sign_download async

sign_download(job_id: str, artifact_id: str, request: JsonObject) -> JsonObject

Sign a fenced artifact download.

Source code in agent_k/api.py
683
684
685
686
687
688
689
690
async def sign_download(
    self,
    job_id: str,
    artifact_id: str,
    request: JsonObject,
) -> JsonObject:
    """Sign a fenced artifact download."""
    ...

complete_upload async

complete_upload(job_id: str, artifact_id: str, request: JsonObject) -> JsonObject

Verify and finalize one artifact upload.

Source code in agent_k/api.py
692
693
694
695
696
697
698
699
async def complete_upload(
    self,
    job_id: str,
    artifact_id: str,
    request: JsonObject,
) -> JsonObject:
    """Verify and finalize one artifact upload."""
    ...

create_migration async

create_migration(request: JsonObject) -> JsonObject

Create a signed legacy-state upload.

Source code in agent_k/api.py
701
702
703
async def create_migration(self, request: JsonObject) -> JsonObject:
    """Create a signed legacy-state upload."""
    ...

complete_migration async

complete_migration(migration_id: str, request: JsonObject) -> JsonObject

Verify and enqueue one legacy-state migration.

Source code in agent_k/api.py
705
706
707
708
709
710
711
async def complete_migration(
    self,
    migration_id: str,
    request: JsonObject,
) -> JsonObject:
    """Verify and enqueue one legacy-state migration."""
    ...

CompetitionGateway

Bases: Protocol

Real competition platform operations exposed to authenticated users.

Source code in agent_k/api.py
714
715
716
717
718
719
720
721
722
723
class CompetitionGateway(Protocol):
    """Real competition platform operations exposed to authenticated users."""

    async def search(self, request: JsonObject) -> list[JsonObject]:
        """Search real competitions with validated filters."""
        ...

    async def fetch(self, url: str) -> JsonObject:
        """Fetch one exact competition by URL."""
        ...

search async

search(request: JsonObject) -> list[JsonObject]

Search real competitions with validated filters.

Source code in agent_k/api.py
717
718
719
async def search(self, request: JsonObject) -> list[JsonObject]:
    """Search real competitions with validated filters."""
    ...

fetch async

fetch(url: str) -> JsonObject

Fetch one exact competition by URL.

Source code in agent_k/api.py
721
722
723
async def fetch(self, url: str) -> JsonObject:
    """Fetch one exact competition by URL."""
    ...

ApiRuntime dataclass

Lifespan-owned API dependencies.

Source code in agent_k/api.py
726
727
728
729
730
731
732
733
734
@dataclass(slots=True)
class ApiRuntime:
    """Lifespan-owned API dependencies."""

    store: RuntimeStore
    artifacts: SignedArtifactStore | None
    competitions: CompetitionGateway | None
    gateway_verifier: GatewayVerifier
    worker_verifier: WorkerVerifier

create_app

create_app(runtime_factory: RuntimeFactory | None = None) -> FastAPI

Create the FastAPI application without import-time resource access.

Parameters:

Name Type Description Default
runtime_factory RuntimeFactory | None

Lifespan context that owns stores and external clients.

None

Returns:

Type Description
FastAPI

A configured FastAPI application.

Source code in agent_k/api.py
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
def create_app(runtime_factory: RuntimeFactory | None = None) -> FastAPI:
    """Create the FastAPI application without import-time resource access.

    Args:
        runtime_factory: Lifespan context that owns stores and external clients.

    Returns:
        A configured FastAPI application.
    """
    factory = runtime_factory or _default_runtime_factory

    @asynccontextmanager
    async def lifespan(application: FastAPI) -> AsyncIterator[None]:
        async with factory() as runtime:
            application.state.runtime = runtime
            with logfire.instrument_fastapi(
                application,
                capture_headers=False,
                request_attributes_mapper=_safe_request_attributes,
            ):
                yield

    application = FastAPI(
        title="AGENT-K API",
        version=__version__,
        lifespan=lifespan,
    )
    _install_error_handlers(application)
    _install_request_id_middleware(application)
    _install_public_routes(application)
    _install_worker_routes(application)
    return application

main

main() -> None

Run the production API entry point.

Source code in agent_k/api.py
1909
1910
1911
1912
1913
def main() -> None:
    """Run the production API entry point."""
    import uvicorn

    uvicorn.run("agent_k.api:app", host=DEFAULT_HOST, port=DEFAULT_PORT)

Define durable mission events and browser-compatible SSE serialization.

(c) Mike Casale 2026. Licensed under the MIT License.

WorkerEvent

Bases: _WireModel

Event submitted by a leased worker.

Source code in agent_k/events.py
111
112
113
114
115
116
117
118
class WorkerEvent(_WireModel):
    """Event submitted by a leased worker."""

    event_id: str = Field(min_length=1, max_length=200)
    sequence: int = Field(ge=1)
    type: EventType
    timestamp: datetime
    data: EventData = Field(default_factory=dict)

AgentKEvent

Bases: WorkerEvent

Durable event associated with a mission.

Source code in agent_k/events.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
class AgentKEvent(WorkerEvent):
    """Durable event associated with a mission."""

    schema_version: str = SCHEMA_VERSION
    mission_id: str = Field(min_length=1, max_length=200)

    def to_browser_event(self) -> BrowserEvent:
        """Return the stable event envelope consumed by the frontend."""
        return BrowserEvent(type=self.type, timestamp=self.timestamp, data=self.data)

    def to_sse(self) -> str:
        """Serialize the event as an ordered, resumable SSE frame."""
        payload = self.to_browser_event().model_dump_json(
            by_alias=True,
            exclude_none=True,
        )
        return f"id: {self.sequence}\ndata: {payload}\n\n"

to_browser_event

to_browser_event() -> BrowserEvent

Return the stable event envelope consumed by the frontend.

Source code in agent_k/events.py
127
128
129
def to_browser_event(self) -> BrowserEvent:
    """Return the stable event envelope consumed by the frontend."""
    return BrowserEvent(type=self.type, timestamp=self.timestamp, data=self.data)

to_sse

to_sse() -> str

Serialize the event as an ordered, resumable SSE frame.

Source code in agent_k/events.py
131
132
133
134
135
136
137
def to_sse(self) -> str:
    """Serialize the event as an ordered, resumable SSE frame."""
    payload = self.to_browser_event().model_dump_json(
        by_alias=True,
        exclude_none=True,
    )
    return f"id: {self.sequence}\ndata: {payload}\n\n"

BrowserEvent

Bases: _WireModel

Stable event envelope exposed to browser clients.

Source code in agent_k/events.py
140
141
142
143
144
145
class BrowserEvent(_WireModel):
    """Stable event envelope exposed to browser clients."""

    type: EventType
    timestamp: datetime
    data: EventData = Field(default_factory=dict)

EventSink

Bases: Protocol

Append mission events to a durable ordered store.

Source code in agent_k/events.py
148
149
150
151
152
153
154
155
156
157
158
159
160
class EventSink(Protocol):
    """Append mission events to a durable ordered store."""

    async def append_event(
        self,
        mission_id: str,
        event_type: EventType,
        data: EventData,
        *,
        timestamp: datetime,
    ) -> AgentKEvent:
        """Append one event and return its assigned durable identity."""
        ...

append_event async

append_event(mission_id: str, event_type: EventType, data: EventData, *, timestamp: datetime) -> AgentKEvent

Append one event and return its assigned durable identity.

Source code in agent_k/events.py
151
152
153
154
155
156
157
158
159
160
async def append_event(
    self,
    mission_id: str,
    event_type: EventType,
    data: EventData,
    *,
    timestamp: datetime,
) -> AgentKEvent:
    """Append one event and return its assigned durable identity."""
    ...

EventEmitter dataclass

Emit camelCase mission events through a durable event sink.

Source code in agent_k/events.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
@dataclass(slots=True)
class EventEmitter:
    """Emit camelCase mission events through a durable event sink."""

    mission_id: str
    sink: EventSink

    async def emit(
        self,
        event_type: EventType,
        data: EventData,
    ) -> AgentKEvent:
        """Append one event to the mission's ordered stream.

        Args:
            event_type: Stable browser-facing event name.
            data: JSON-compatible camelCase event payload.

        Returns:
            The durable event with its assigned sequence and identifier.
        """
        event = await self.sink.append_event(
            self.mission_id,
            event_type,
            data,
            timestamp=datetime.now(UTC),
        )
        logfire.debug(
            "mission_event_appended",
            mission_id=self.mission_id,
            event_type=event_type,
            sequence=event.sequence,
        )
        return event

    async def emit_phase_start(
        self,
        phase: str,
        objectives: list[str],
    ) -> AgentKEvent:
        """Emit a phase-start event."""
        return await self.emit(
            "phase-start",
            {"phase": phase, "objectives": cast(list[JsonValue], objectives)},
        )

    async def emit_phase_complete(
        self,
        phase: str,
        success: bool,
        duration_ms: int,
    ) -> AgentKEvent:
        """Emit a phase-complete event."""
        return await self.emit(
            "phase-complete",
            {"phase": phase, "success": success, "durationMs": duration_ms},
        )

    async def emit_phase_error(
        self,
        phase: str,
        error: str,
        recoverable: bool,
    ) -> AgentKEvent:
        """Emit a phase-error event."""
        return await self.emit(
            "phase-error",
            {"phase": phase, "error": error, "recoverable": recoverable},
        )

    async def emit_task_start(
        self,
        task_id: str,
        phase: str,
        name: str,
    ) -> AgentKEvent:
        """Emit a task-start event."""
        return await self.emit(
            "task-start",
            {"taskId": task_id, "phase": phase, "name": name},
        )

    async def emit_task_progress(
        self,
        task_id: str,
        progress: float,
        message: str | None = None,
    ) -> AgentKEvent:
        """Emit a task-progress event."""
        return await self.emit(
            "task-progress",
            {"taskId": task_id, "progress": progress, "message": message},
        )

    async def emit_task_complete(
        self,
        task_id: str,
        success: bool,
        result: EventData = None,
        duration_ms: int = 0,
    ) -> AgentKEvent:
        """Emit a task-complete event."""
        return await self.emit(
            "task-complete",
            {
                "taskId": task_id,
                "success": success,
                "result": result,
                "durationMs": duration_ms,
            },
        )

    async def emit_tool_start(
        self,
        task_id: str,
        tool_call_id: str,
        tool_type: str,
        operation: str,
        params: dict[str, EventData] | None = None,
    ) -> AgentKEvent:
        """Emit a tool-start event."""
        return await self.emit(
            "tool-start",
            {
                "taskId": task_id,
                "toolCallId": tool_call_id,
                "toolType": tool_type,
                "operation": operation,
                "params": params,
            },
        )

    async def emit_tool_thinking(
        self,
        task_id: str,
        tool_call_id: str,
        chunk: str,
    ) -> AgentKEvent:
        """Emit a tool-thinking event."""
        return await self.emit(
            "tool-thinking",
            {"taskId": task_id, "toolCallId": tool_call_id, "chunk": chunk},
        )

    async def emit_tool_result(
        self,
        task_id: str,
        tool_call_id: str,
        result: EventData,
        duration_ms: int,
    ) -> AgentKEvent:
        """Emit a tool-result event."""
        return await self.emit(
            "tool-result",
            {
                "taskId": task_id,
                "toolCallId": tool_call_id,
                "result": result,
                "durationMs": duration_ms,
            },
        )

    async def emit_tool_error(
        self,
        task_id: str,
        tool_call_id: str,
        error: str,
    ) -> AgentKEvent:
        """Emit a tool-error event."""
        return await self.emit(
            "tool-error",
            {"taskId": task_id, "toolCallId": tool_call_id, "error": error},
        )

    async def emit_generation_start(
        self,
        generation: int,
        population_size: int,
        *,
        model_family: ModelFamily | None = None,
        model_size: ModelSize | None = None,
        iteration: int | None = None,
        total_iterations: int | None = None,
    ) -> AgentKEvent:
        """Emit a generation-start event with optional runtime metadata."""
        return await self.emit(
            "generation-start",
            {
                "generation": generation,
                "populationSize": population_size,
                "modelFamily": model_family,
                "modelSize": model_size,
                "iteration": iteration,
                "totalIterations": total_iterations,
            },
        )

    async def emit_generation_complete(
        self,
        generation: int,
        best_fitness: float,
        mean_fitness: float,
        worst_fitness: float,
        population_size: int,
        mutations: dict[str, int],
        *,
        model_family: ModelFamily | None = None,
        model_size: ModelSize | None = None,
        iteration: int | None = None,
        total_iterations: int | None = None,
    ) -> AgentKEvent:
        """Emit a generation-complete event."""
        return await self.emit(
            "generation-complete",
            {
                "generation": generation,
                "bestFitness": best_fitness,
                "meanFitness": mean_fitness,
                "worstFitness": worst_fitness,
                "populationSize": population_size,
                "mutations": {
                    "point": mutations.get("point", 0),
                    "structural": mutations.get("structural", 0),
                    "hyperparameter": mutations.get("hyperparameter", 0),
                    "crossover": mutations.get("crossover", 0),
                },
                "timestamp": datetime.now(UTC).isoformat(),
                "modelFamily": model_family,
                "modelSize": model_size,
                "iteration": iteration,
                "totalIterations": total_iterations,
            },
        )

    async def emit_submission_result(
        self,
        submission_id: str,
        generation: int,
        cv_score: float,
        public_score: float | None,
        rank: int | None,
        total_teams: int | None,
    ) -> AgentKEvent:
        """Emit a submission-result event."""
        percentile = (rank / total_teams * 100) if rank and total_teams else None
        return await self.emit(
            "submission-result",
            {
                "submissionId": submission_id,
                "generation": generation,
                "cvScore": cv_score,
                "publicScore": public_score,
                "rank": rank,
                "totalTeams": total_teams,
                "percentile": percentile,
                "submittedAt": datetime.now(UTC).isoformat(),
            },
        )

    async def emit_convergence_detected(
        self,
        generation: int,
        reason: str,
    ) -> AgentKEvent:
        """Emit a convergence-detected event."""
        return await self.emit(
            "convergence-detected",
            {"generation": generation, "reason": reason},
        )

    async def emit_memory_store(
        self,
        key: str,
        scope: str,
        category: str,
    ) -> AgentKEvent:
        """Emit a memory-store event."""
        return await self.emit(
            "memory-store",
            {"key": key, "scope": scope, "category": category},
        )

    async def emit_memory_retrieve(
        self,
        key: str,
        found: bool,
    ) -> AgentKEvent:
        """Emit a memory-retrieve event."""
        return await self.emit("memory-retrieve", {"key": key, "found": found})

    async def emit_checkpoint_created(
        self,
        name: str,
        phase: str,
    ) -> AgentKEvent:
        """Emit a checkpoint-created event."""
        return await self.emit(
            "checkpoint-created",
            {"name": name, "phase": phase},
        )

    async def emit_error(
        self,
        error_id: str,
        category: str,
        error_type: str,
        message: str,
        context: str,
        recovery_strategy: str,
    ) -> AgentKEvent:
        """Emit an error-occurred event."""
        return await self.emit(
            "error-occurred",
            {
                "id": error_id,
                "timestamp": datetime.now(UTC).isoformat(),
                "category": category,
                "errorType": error_type,
                "message": message,
                "context": context,
                "recoveryStrategy": recovery_strategy,
                "recoveryAttempts": 0,
                "resolved": False,
            },
        )

    async def emit_recovery_attempt(
        self,
        error_id: str,
        strategy: str,
        attempt: int,
    ) -> AgentKEvent:
        """Emit a recovery-attempt event."""
        return await self.emit(
            "recovery-attempt",
            {"errorId": error_id, "strategy": strategy, "attempt": attempt},
        )

    async def emit_recovery_complete(
        self,
        error_id: str,
        success: bool,
        resolution: str | None = None,
    ) -> AgentKEvent:
        """Emit a recovery-complete event."""
        return await self.emit(
            "recovery-complete",
            {"errorId": error_id, "success": success, "resolution": resolution},
        )

    async def emit_mission_complete(
        self,
        *,
        success: bool,
        final_rank: int | None,
        final_score: float | None,
        error_message: str | None = None,
        total_submissions: int,
        evolution_generations: int,
        evolution_iterations: int | None = None,
        duration_ms: int,
        phases_completed: list[str],
        evolution_failure_summary: dict[str, int] | None = None,
    ) -> AgentKEvent:
        """Emit the canonical camelCase mission-complete event."""
        return await self.emit(
            "mission-complete",
            {
                "success": success,
                "finalRank": final_rank,
                "finalScore": final_score,
                "errorMessage": error_message,
                "totalSubmissions": total_submissions,
                "evolutionGenerations": evolution_generations,
                "evolutionIterations": evolution_iterations,
                "evolutionFailureSummary": cast(
                    dict[str, JsonValue],
                    evolution_failure_summary or {},
                ),
                "durationMs": duration_ms,
                "phasesCompleted": cast(list[JsonValue], phases_completed),
            },
        )

emit async

emit(event_type: EventType, data: EventData) -> AgentKEvent

Append one event to the mission's ordered stream.

Parameters:

Name Type Description Default
event_type EventType

Stable browser-facing event name.

required
data EventData

JSON-compatible camelCase event payload.

required

Returns:

Type Description
AgentKEvent

The durable event with its assigned sequence and identifier.

Source code in agent_k/events.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
async def emit(
    self,
    event_type: EventType,
    data: EventData,
) -> AgentKEvent:
    """Append one event to the mission's ordered stream.

    Args:
        event_type: Stable browser-facing event name.
        data: JSON-compatible camelCase event payload.

    Returns:
        The durable event with its assigned sequence and identifier.
    """
    event = await self.sink.append_event(
        self.mission_id,
        event_type,
        data,
        timestamp=datetime.now(UTC),
    )
    logfire.debug(
        "mission_event_appended",
        mission_id=self.mission_id,
        event_type=event_type,
        sequence=event.sequence,
    )
    return event

emit_phase_start async

emit_phase_start(phase: str, objectives: list[str]) -> AgentKEvent

Emit a phase-start event.

Source code in agent_k/events.py
198
199
200
201
202
203
204
205
206
207
async def emit_phase_start(
    self,
    phase: str,
    objectives: list[str],
) -> AgentKEvent:
    """Emit a phase-start event."""
    return await self.emit(
        "phase-start",
        {"phase": phase, "objectives": cast(list[JsonValue], objectives)},
    )

emit_phase_complete async

emit_phase_complete(phase: str, success: bool, duration_ms: int) -> AgentKEvent

Emit a phase-complete event.

Source code in agent_k/events.py
209
210
211
212
213
214
215
216
217
218
219
async def emit_phase_complete(
    self,
    phase: str,
    success: bool,
    duration_ms: int,
) -> AgentKEvent:
    """Emit a phase-complete event."""
    return await self.emit(
        "phase-complete",
        {"phase": phase, "success": success, "durationMs": duration_ms},
    )

emit_phase_error async

emit_phase_error(phase: str, error: str, recoverable: bool) -> AgentKEvent

Emit a phase-error event.

Source code in agent_k/events.py
221
222
223
224
225
226
227
228
229
230
231
async def emit_phase_error(
    self,
    phase: str,
    error: str,
    recoverable: bool,
) -> AgentKEvent:
    """Emit a phase-error event."""
    return await self.emit(
        "phase-error",
        {"phase": phase, "error": error, "recoverable": recoverable},
    )

emit_task_start async

emit_task_start(task_id: str, phase: str, name: str) -> AgentKEvent

Emit a task-start event.

Source code in agent_k/events.py
233
234
235
236
237
238
239
240
241
242
243
async def emit_task_start(
    self,
    task_id: str,
    phase: str,
    name: str,
) -> AgentKEvent:
    """Emit a task-start event."""
    return await self.emit(
        "task-start",
        {"taskId": task_id, "phase": phase, "name": name},
    )

emit_task_progress async

emit_task_progress(task_id: str, progress: float, message: str | None = None) -> AgentKEvent

Emit a task-progress event.

Source code in agent_k/events.py
245
246
247
248
249
250
251
252
253
254
255
async def emit_task_progress(
    self,
    task_id: str,
    progress: float,
    message: str | None = None,
) -> AgentKEvent:
    """Emit a task-progress event."""
    return await self.emit(
        "task-progress",
        {"taskId": task_id, "progress": progress, "message": message},
    )

emit_task_complete async

emit_task_complete(task_id: str, success: bool, result: EventData = None, duration_ms: int = 0) -> AgentKEvent

Emit a task-complete event.

Source code in agent_k/events.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
async def emit_task_complete(
    self,
    task_id: str,
    success: bool,
    result: EventData = None,
    duration_ms: int = 0,
) -> AgentKEvent:
    """Emit a task-complete event."""
    return await self.emit(
        "task-complete",
        {
            "taskId": task_id,
            "success": success,
            "result": result,
            "durationMs": duration_ms,
        },
    )

emit_tool_start async

emit_tool_start(task_id: str, tool_call_id: str, tool_type: str, operation: str, params: dict[str, EventData] | None = None) -> AgentKEvent

Emit a tool-start event.

Source code in agent_k/events.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
async def emit_tool_start(
    self,
    task_id: str,
    tool_call_id: str,
    tool_type: str,
    operation: str,
    params: dict[str, EventData] | None = None,
) -> AgentKEvent:
    """Emit a tool-start event."""
    return await self.emit(
        "tool-start",
        {
            "taskId": task_id,
            "toolCallId": tool_call_id,
            "toolType": tool_type,
            "operation": operation,
            "params": params,
        },
    )

emit_tool_thinking async

emit_tool_thinking(task_id: str, tool_call_id: str, chunk: str) -> AgentKEvent

Emit a tool-thinking event.

Source code in agent_k/events.py
295
296
297
298
299
300
301
302
303
304
305
async def emit_tool_thinking(
    self,
    task_id: str,
    tool_call_id: str,
    chunk: str,
) -> AgentKEvent:
    """Emit a tool-thinking event."""
    return await self.emit(
        "tool-thinking",
        {"taskId": task_id, "toolCallId": tool_call_id, "chunk": chunk},
    )

emit_tool_result async

emit_tool_result(task_id: str, tool_call_id: str, result: EventData, duration_ms: int) -> AgentKEvent

Emit a tool-result event.

Source code in agent_k/events.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
async def emit_tool_result(
    self,
    task_id: str,
    tool_call_id: str,
    result: EventData,
    duration_ms: int,
) -> AgentKEvent:
    """Emit a tool-result event."""
    return await self.emit(
        "tool-result",
        {
            "taskId": task_id,
            "toolCallId": tool_call_id,
            "result": result,
            "durationMs": duration_ms,
        },
    )

emit_tool_error async

emit_tool_error(task_id: str, tool_call_id: str, error: str) -> AgentKEvent

Emit a tool-error event.

Source code in agent_k/events.py
325
326
327
328
329
330
331
332
333
334
335
async def emit_tool_error(
    self,
    task_id: str,
    tool_call_id: str,
    error: str,
) -> AgentKEvent:
    """Emit a tool-error event."""
    return await self.emit(
        "tool-error",
        {"taskId": task_id, "toolCallId": tool_call_id, "error": error},
    )

emit_generation_start async

emit_generation_start(generation: int, population_size: int, *, model_family: ModelFamily | None = None, model_size: ModelSize | None = None, iteration: int | None = None, total_iterations: int | None = None) -> AgentKEvent

Emit a generation-start event with optional runtime metadata.

Source code in agent_k/events.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
async def emit_generation_start(
    self,
    generation: int,
    population_size: int,
    *,
    model_family: ModelFamily | None = None,
    model_size: ModelSize | None = None,
    iteration: int | None = None,
    total_iterations: int | None = None,
) -> AgentKEvent:
    """Emit a generation-start event with optional runtime metadata."""
    return await self.emit(
        "generation-start",
        {
            "generation": generation,
            "populationSize": population_size,
            "modelFamily": model_family,
            "modelSize": model_size,
            "iteration": iteration,
            "totalIterations": total_iterations,
        },
    )

emit_generation_complete async

emit_generation_complete(generation: int, best_fitness: float, mean_fitness: float, worst_fitness: float, population_size: int, mutations: dict[str, int], *, model_family: ModelFamily | None = None, model_size: ModelSize | None = None, iteration: int | None = None, total_iterations: int | None = None) -> AgentKEvent

Emit a generation-complete event.

Source code in agent_k/events.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
async def emit_generation_complete(
    self,
    generation: int,
    best_fitness: float,
    mean_fitness: float,
    worst_fitness: float,
    population_size: int,
    mutations: dict[str, int],
    *,
    model_family: ModelFamily | None = None,
    model_size: ModelSize | None = None,
    iteration: int | None = None,
    total_iterations: int | None = None,
) -> AgentKEvent:
    """Emit a generation-complete event."""
    return await self.emit(
        "generation-complete",
        {
            "generation": generation,
            "bestFitness": best_fitness,
            "meanFitness": mean_fitness,
            "worstFitness": worst_fitness,
            "populationSize": population_size,
            "mutations": {
                "point": mutations.get("point", 0),
                "structural": mutations.get("structural", 0),
                "hyperparameter": mutations.get("hyperparameter", 0),
                "crossover": mutations.get("crossover", 0),
            },
            "timestamp": datetime.now(UTC).isoformat(),
            "modelFamily": model_family,
            "modelSize": model_size,
            "iteration": iteration,
            "totalIterations": total_iterations,
        },
    )

emit_submission_result async

emit_submission_result(submission_id: str, generation: int, cv_score: float, public_score: float | None, rank: int | None, total_teams: int | None) -> AgentKEvent

Emit a submission-result event.

Source code in agent_k/events.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
async def emit_submission_result(
    self,
    submission_id: str,
    generation: int,
    cv_score: float,
    public_score: float | None,
    rank: int | None,
    total_teams: int | None,
) -> AgentKEvent:
    """Emit a submission-result event."""
    percentile = (rank / total_teams * 100) if rank and total_teams else None
    return await self.emit(
        "submission-result",
        {
            "submissionId": submission_id,
            "generation": generation,
            "cvScore": cv_score,
            "publicScore": public_score,
            "rank": rank,
            "totalTeams": total_teams,
            "percentile": percentile,
            "submittedAt": datetime.now(UTC).isoformat(),
        },
    )

emit_convergence_detected async

emit_convergence_detected(generation: int, reason: str) -> AgentKEvent

Emit a convergence-detected event.

Source code in agent_k/events.py
422
423
424
425
426
427
428
429
430
431
async def emit_convergence_detected(
    self,
    generation: int,
    reason: str,
) -> AgentKEvent:
    """Emit a convergence-detected event."""
    return await self.emit(
        "convergence-detected",
        {"generation": generation, "reason": reason},
    )

emit_memory_store async

emit_memory_store(key: str, scope: str, category: str) -> AgentKEvent

Emit a memory-store event.

Source code in agent_k/events.py
433
434
435
436
437
438
439
440
441
442
443
async def emit_memory_store(
    self,
    key: str,
    scope: str,
    category: str,
) -> AgentKEvent:
    """Emit a memory-store event."""
    return await self.emit(
        "memory-store",
        {"key": key, "scope": scope, "category": category},
    )

emit_memory_retrieve async

emit_memory_retrieve(key: str, found: bool) -> AgentKEvent

Emit a memory-retrieve event.

Source code in agent_k/events.py
445
446
447
448
449
450
451
async def emit_memory_retrieve(
    self,
    key: str,
    found: bool,
) -> AgentKEvent:
    """Emit a memory-retrieve event."""
    return await self.emit("memory-retrieve", {"key": key, "found": found})

emit_checkpoint_created async

emit_checkpoint_created(name: str, phase: str) -> AgentKEvent

Emit a checkpoint-created event.

Source code in agent_k/events.py
453
454
455
456
457
458
459
460
461
462
async def emit_checkpoint_created(
    self,
    name: str,
    phase: str,
) -> AgentKEvent:
    """Emit a checkpoint-created event."""
    return await self.emit(
        "checkpoint-created",
        {"name": name, "phase": phase},
    )

emit_error async

emit_error(error_id: str, category: str, error_type: str, message: str, context: str, recovery_strategy: str) -> AgentKEvent

Emit an error-occurred event.

Source code in agent_k/events.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
async def emit_error(
    self,
    error_id: str,
    category: str,
    error_type: str,
    message: str,
    context: str,
    recovery_strategy: str,
) -> AgentKEvent:
    """Emit an error-occurred event."""
    return await self.emit(
        "error-occurred",
        {
            "id": error_id,
            "timestamp": datetime.now(UTC).isoformat(),
            "category": category,
            "errorType": error_type,
            "message": message,
            "context": context,
            "recoveryStrategy": recovery_strategy,
            "recoveryAttempts": 0,
            "resolved": False,
        },
    )

emit_recovery_attempt async

emit_recovery_attempt(error_id: str, strategy: str, attempt: int) -> AgentKEvent

Emit a recovery-attempt event.

Source code in agent_k/events.py
489
490
491
492
493
494
495
496
497
498
499
async def emit_recovery_attempt(
    self,
    error_id: str,
    strategy: str,
    attempt: int,
) -> AgentKEvent:
    """Emit a recovery-attempt event."""
    return await self.emit(
        "recovery-attempt",
        {"errorId": error_id, "strategy": strategy, "attempt": attempt},
    )

emit_recovery_complete async

emit_recovery_complete(error_id: str, success: bool, resolution: str | None = None) -> AgentKEvent

Emit a recovery-complete event.

Source code in agent_k/events.py
501
502
503
504
505
506
507
508
509
510
511
async def emit_recovery_complete(
    self,
    error_id: str,
    success: bool,
    resolution: str | None = None,
) -> AgentKEvent:
    """Emit a recovery-complete event."""
    return await self.emit(
        "recovery-complete",
        {"errorId": error_id, "success": success, "resolution": resolution},
    )

emit_mission_complete async

emit_mission_complete(*, success: bool, final_rank: int | None, final_score: float | None, error_message: str | None = None, total_submissions: int, evolution_generations: int, evolution_iterations: int | None = None, duration_ms: int, phases_completed: list[str], evolution_failure_summary: dict[str, int] | None = None) -> AgentKEvent

Emit the canonical camelCase mission-complete event.

Source code in agent_k/events.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
async def emit_mission_complete(
    self,
    *,
    success: bool,
    final_rank: int | None,
    final_score: float | None,
    error_message: str | None = None,
    total_submissions: int,
    evolution_generations: int,
    evolution_iterations: int | None = None,
    duration_ms: int,
    phases_completed: list[str],
    evolution_failure_summary: dict[str, int] | None = None,
) -> AgentKEvent:
    """Emit the canonical camelCase mission-complete event."""
    return await self.emit(
        "mission-complete",
        {
            "success": success,
            "finalRank": final_rank,
            "finalScore": final_score,
            "errorMessage": error_message,
            "totalSubmissions": total_submissions,
            "evolutionGenerations": evolution_generations,
            "evolutionIterations": evolution_iterations,
            "evolutionFailureSummary": cast(
                dict[str, JsonValue],
                evolution_failure_summary or {},
            ),
            "durationMs": duration_ms,
            "phasesCompleted": cast(list[JsonValue], phases_completed),
        },
    )

parse_last_event_id

parse_last_event_id(value: str | None) -> int

Parse an SSE Last-Event-ID value into the last delivered sequence.

Parameters:

Name Type Description Default
value str | None

Header value supplied by the browser, or None.

required

Returns:

Type Description
int

The non-negative last delivered event sequence.

Raises:

Type Description
ValueError

If the value is not a non-negative integer.

Source code in agent_k/events.py
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
def parse_last_event_id(value: str | None) -> int:
    """Parse an SSE Last-Event-ID value into the last delivered sequence.

    Args:
        value: Header value supplied by the browser, or ``None``.

    Returns:
        The non-negative last delivered event sequence.

    Raises:
        ValueError: If the value is not a non-negative integer.
    """
    if value is None or not value.strip():
        return 0
    try:
        sequence = int(value)
    except ValueError as exc:
        raise ValueError("Last-Event-ID must be a non-negative integer") from exc
    if sequence < 0:
        raise ValueError("Last-Event-ID must be a non-negative integer")
    return sequence

Classify mission intent without import-time model or network access.

(c) Mike Casale 2026. Licensed under the MIT License.

CompetitionType

Bases: StrEnum

Type of Kaggle competition.

Source code in agent_k/models.py
33
34
35
36
37
38
39
40
class CompetitionType(StrEnum):
    """Type of Kaggle competition."""

    FEATURED = "featured"
    RESEARCH = "research"
    GETTING_STARTED = "getting_started"
    PLAYGROUND = "playground"
    COMMUNITY = "community"

MissionCriteriaInput

Bases: BaseModel

Criteria constraining mission execution.

Source code in agent_k/models.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
class MissionCriteria(BaseModel):
    """Criteria constraining mission execution."""

    model_config = ConfigDict(
        frozen=True,
        alias_generator=to_camel,
        populate_by_name=True,
        extra="forbid",
    )
    schema_version: str = Field(default=SCHEMA_VERSION, description="Schema version")
    target_competition_types: frozenset[CompetitionType] = Field(
        default=frozenset({CompetitionType.FEATURED, CompetitionType.RESEARCH}),
        description="Target competition types",
    )
    min_prize_pool: int | None = Field(default=None, ge=0, description="Minimum prize pool")
    max_team_size: int | None = Field(default=None, ge=1, description="Maximum team size")
    min_days_remaining: int = Field(default=7, ge=1, description="Minimum days remaining")
    target_domains: frozenset[str] = Field(default_factory=frozenset, description="Target domains")
    exclude_domains: frozenset[str] = Field(
        default_factory=frozenset, description="Excluded domains"
    )
    max_evolution_rounds: int = Field(
        default=100, ge=1, le=MAX_MISSION_EVOLUTION_ROUNDS, description="Max evolution rounds"
    )
    min_improvements_required: int = Field(
        default=0,
        ge=0,
        description="Minimum number of fitness improvements required before submission",
    )
    target_leaderboard_percentile: float = Field(
        default=0.10, ge=0.0, le=1.0, description="Target top N percentile on leaderboard"
    )
    evolution_models: tuple[str, ...] = Field(
        default_factory=tuple, description="Ordered model specs to rotate during evolution"
    )
    enable_kumo: bool = True
    allow_submission: bool = False
    min_evolution_iterations: int = Field(default=1, ge=1, le=200)
    use_openevolve: bool = Field(default=True, description="Deprecated; OpenEvolve is always used")

    @model_validator(mode="after")
    def validate_domains_disjoint(self) -> Self:
        """Ensure target and exclude domains don't overlap."""
        overlap = self.target_domains & self.exclude_domains
        if overlap:
            raise ValueError(f"Domains cannot be both targeted and excluded: {overlap}")
        if self.min_evolution_iterations > self.max_evolution_rounds:
            raise ValueError("Minimum evolution iterations exceed the maximum")
        if self.min_improvements_required > self.max_evolution_rounds:
            raise ValueError("Minimum improvements exceed the available iterations")
        return self

validate_domains_disjoint

validate_domains_disjoint() -> Self

Ensure target and exclude domains don't overlap.

Source code in agent_k/models.py
203
204
205
206
207
208
209
210
211
212
213
@model_validator(mode="after")
def validate_domains_disjoint(self) -> Self:
    """Ensure target and exclude domains don't overlap."""
    overlap = self.target_domains & self.exclude_domains
    if overlap:
        raise ValueError(f"Domains cannot be both targeted and excluded: {overlap}")
    if self.min_evolution_iterations > self.max_evolution_rounds:
        raise ValueError("Minimum evolution iterations exceed the maximum")
    if self.min_improvements_required > self.max_evolution_rounds:
        raise ValueError("Minimum improvements exceed the available iterations")
    return self

MissionIntentResult

Bases: BaseModel

Deterministic classification result for one user message.

Source code in agent_k/intent.py
79
80
81
82
83
84
85
class MissionIntentResult(BaseModel):
    """Deterministic classification result for one user message."""

    model_config = ConfigDict(frozen=True)

    is_mission: bool
    criteria: MissionCriteriaInput | None = None

MissionIntentParser dataclass

Extract mission intent and criteria using deterministic language rules.

Source code in agent_k/intent.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
@dataclass(frozen=True, slots=True)
class MissionIntentParser:
    """Extract mission intent and criteria using deterministic language rules."""

    mission_actions: tuple[str, ...] = _MISSION_ACTIONS
    mission_objects: tuple[str, ...] = _MISSION_OBJECTS

    def parse(self, message: str) -> MissionIntentResult:
        """Classify one message and extract supported mission criteria.

        Args:
            message: User-authored text from the latest chat message.

        Returns:
            A classification and validated criteria for mission requests.
        """
        normalized = " ".join(message.lower().split())
        if not normalized or normalized.startswith(_EXPLANATION_PREFIXES):
            return MissionIntentResult(is_mission=False)

        has_action = any(_contains_term(normalized, term) for term in self.mission_actions)
        has_object = any(_contains_term(normalized, term) for term in self.mission_objects)
        if not (has_action and has_object):
            return MissionIntentResult(is_mission=False)

        return MissionIntentResult(
            is_mission=True,
            criteria=_extract_criteria(normalized),
        )

parse

parse(message: str) -> MissionIntentResult

Classify one message and extract supported mission criteria.

Parameters:

Name Type Description Default
message str

User-authored text from the latest chat message.

required

Returns:

Type Description
MissionIntentResult

A classification and validated criteria for mission requests.

Source code in agent_k/intent.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def parse(self, message: str) -> MissionIntentResult:
    """Classify one message and extract supported mission criteria.

    Args:
        message: User-authored text from the latest chat message.

    Returns:
        A classification and validated criteria for mission requests.
    """
    normalized = " ".join(message.lower().split())
    if not normalized or normalized.startswith(_EXPLANATION_PREFIXES):
        return MissionIntentResult(is_mission=False)

    has_action = any(_contains_term(normalized, term) for term in self.mission_actions)
    has_object = any(_contains_term(normalized, term) for term in self.mission_objects)
    if not (has_action and has_object):
        return MissionIntentResult(is_mission=False)

    return MissionIntentResult(
        is_mission=True,
        criteria=_extract_criteria(normalized),
    )

parse_mission_intent

parse_mission_intent(messages: list[dict[str, Any]], *, parser: MissionIntentParser | None = None) -> MissionIntentResult

Parse the latest user text from a frontend chat message list.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Vercel AI-style messages with text parts.

required
parser MissionIntentParser | None

Optional deterministic parser configuration.

None

Returns:

Type Description
MissionIntentResult

A non-mission result when no usable user text is present.

Source code in agent_k/intent.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def parse_mission_intent(
    messages: list[dict[str, Any]],
    *,
    parser: MissionIntentParser | None = None,
) -> MissionIntentResult:
    """Parse the latest user text from a frontend chat message list.

    Args:
        messages: Vercel AI-style messages with text parts.
        parser: Optional deterministic parser configuration.

    Returns:
        A non-mission result when no usable user text is present.
    """
    message = extract_latest_user_message(messages)
    if message is None:
        return MissionIntentResult(is_mission=False)
    return (parser or MissionIntentParser()).parse(message)

extract_latest_user_message

extract_latest_user_message(messages: list[dict[str, Any]]) -> str | None

Return text from the latest user message without accepting other roles.

Source code in agent_k/intent.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def extract_latest_user_message(messages: list[dict[str, Any]]) -> str | None:
    """Return text from the latest user message without accepting other roles."""
    for message in reversed(messages):
        if message.get("role") != "user":
            continue
        parts = message.get("parts")
        if not isinstance(parts, list):
            return None
        text_parts = [
            part.get("text", "")
            for part in parts
            if isinstance(part, dict)
            and part.get("type") == "text"
            and isinstance(part.get("text"), str)
        ]
        text = " ".join(text_parts).strip()
        return text or None
    return None

Runtime settings, loaded explicitly by API and worker entry points.

(c) Mike Casale 2026. Licensed under the MIT License.

Settings

Bases: BaseSettings

Validated configuration for a mission process.

Environment names use the AGENT_K_ prefix. Provider and Kaggle credentials stay in the worker environment; none are forwarded to candidate containers.

Source code in agent_k/config.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Settings(BaseSettings):
    """Validated configuration for a mission process.

    Environment names use the ``AGENT_K_`` prefix. Provider and Kaggle credentials
    stay in the worker environment; none are forwarded to candidate containers.
    """

    model_config = SettingsConfigDict(env_prefix="AGENT_K_", extra="ignore")

    environment: str = "development"
    model: str = "devstral:local"
    fallback_models: tuple[str, ...] = ()
    agent_request_limit: int = Field(default=20, ge=1, le=200)
    agent_request_timeout_seconds: int = Field(default=180, ge=5, le=3600)
    database_url: SecretStr | None = None
    s3_bucket: str | None = None
    s3_region: str = "us-east-1"
    gateway_secret: SecretStr | None = Field(default=None, min_length=32)
    gateway_previous_secret: SecretStr | None = Field(default=None, min_length=32)
    gateway_issuer: str = "agent-k-frontend"
    gateway_audience: str = "agent-k-api"
    gateway_token_ttl_seconds: int = Field(default=60, ge=30, le=300)
    worker_token: SecretStr | None = Field(default=None, min_length=32)
    worker_previous_token: SecretStr | None = Field(default=None, min_length=32)
    allow_submissions: bool = False
    phase_timeout_seconds: int = Field(default=3600, ge=60)
    evolution_iterations: int = Field(default=20, ge=1, le=MAX_MISSION_EVOLUTION_ROUNDS)
    evaluation_timeout_seconds: int = Field(default=1200, ge=1)
    evaluation_parallelism: int = Field(default=1, ge=1, le=16)
    sandbox_image: str | None = None
    gpu_devices: tuple[str, ...] = ()
    kumo_cache: Path | None = None
    vision_weights: Path | None = None
    transformer_cache: Path | None = None
    memory_root: Path = Path("/tmp/agent-k/memory")

load_settings

load_settings() -> Settings

Read current environment values without an import-time singleton.

Source code in agent_k/config.py
57
58
59
def load_settings() -> Settings:
    """Read current environment values without an import-time singleton."""
    return Settings()

Logfire instrumentation configured at application startup.

(c) Mike Casale 2026. Licensed under the MIT License.

configure_observability

configure_observability(*, service_name: str, environment: str) -> None

Configure telemetry once in each API, worker, or mission process.

Parameters:

Name Type Description Default
service_name str

Deployment role included in telemetry resource attributes.

required
environment str

Runtime environment included in telemetry resource attributes.

required

Agent instrumentation records timing and usage without prompts, completions, tool content, or binary payloads. A configured Logfire token enables remote export.

Source code in agent_k/observability.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def configure_observability(*, service_name: str, environment: str) -> None:
    """Configure telemetry once in each API, worker, or mission process.

    Args:
        service_name: Deployment role included in telemetry resource attributes.
        environment: Runtime environment included in telemetry resource attributes.

    Agent instrumentation records timing and usage without prompts, completions, tool
    content, or binary payloads. A configured Logfire token enables remote export.
    """
    logfire.configure(
        service_name=service_name,
        environment=environment,
        send_to_logfire="if-token-present",
        console=False,
    )
    Agent.instrument_all(
        InstrumentationSettings(include_content=False, include_binary_content=False)
    )