Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ All notable changes to this project are documented in this file. The format is b
- **`ask_operator` target warning**: a request whose question names a host or URL outside the goal targets is tagged as containing target-derived text (#197).
- **Opt-in update banner**: `ARTEX_UPDATE_CHECK` makes the backend check the latest GitHub release at most once per 24 hours and the UI show a banner; off by default (#202).
- **Release provenance**: release archives carry GitHub build provenance attestations and a CycloneDX SBOM (`gh attestation verify <zip> --repo BaaRai/ARTEX`); release notes are the matching `CHANGELOG.md` section (#219, #201).
- **Opt-in worker cache-prefix split (P3.5 Phase C)**: setting `ARTEX_CACHE_PREFIX=1` (off by default) splits the `worker` system prompt at `DynamicBoundary = 1` into a sibling-shareable static prefix (`body + untrustedContentTail + workerTrafficBlock`) and a per-intent dynamic suffix (`workerArtifactSpec(runDir)` through `<available-deferred-tools>`) without reordering sections or altering the visible joined prompt text. Planner, mainagent, chat, and goals are unchanged; custom worker prompts referencing `{{.Now}}` remain volatile in the static segment. See `docs/context-telemetry.md`.
- **Opt-in LLM context size telemetry (P3.5 Phase A)**: setting `ARTEX_CONTEXT_TELEMETRY=1` (off by default) records per-call request section byte sizes (`system_static`/`system_dynamic` split at `DynamicBoundary`, serialized `tools`, `messages` by role, `tool_result` subset, and `last_message_bytes`), tool/message counts, and token/cache usage in the new `llm_context` table (migration `0009_llm_context.sql`), with zero prompt/behavior change and zero content stored, independent of `llm_record`. `GET /api/llm/context/summary` aggregates input percentiles (`p50`/`p90`/`p99`), pro-rata section shares over real `input_tokens`, `cache_read/input` ratios by `(worker, model)`, and top tasks. See `docs/context-telemetry.md`.
- **HAR 1.2 traffic import and export**: `POST /api/traffic/import/har` imports raw HAR 1.2 JSON captures (up to 32 MiB / 2,000 entries / 32 MiB decoded bodies) with deterministic `har-<sha256>` IDs (and `_artexExchangeId` preservation for ARTEX exports so distinct same-second exchanges round-trip without collapsing), base64 decoding, `postData.params` and `cookies` array fallbacks, URL userinfo stripping, blob spilling above 256 KiB, and full-text indexing, without applying capture rewrite rules (`exchange_rewrites` stays empty); per-entry errors are reported alongside `imported`/`skipped`/`failed` counts. `GET /api/traffic/export/har` exports filtered traffic (reusing the `GET /api/traffic` filters) as a compliant HAR 1.2 document (with explicit unknown placeholders for unrecorded timings and header sizes) in stable `(ts, id)` order, encoding UTF-8 bodies as text and binary bodies as base64, capped at 1,000 entries / 20 MiB raw headers+bodies (31 MiB JSON backstop, guaranteed under the 32 MiB import limit) with explicit truncation reporting via `X-ARTEX-HAR-*` headers and `_truncated`/`_truncatedReason`/`_totalMatched` fields. The Traffic page adds **Import HAR** and **Export HAR** controls. See `docs/traffic-har.md`.
- **Capture-proxy rewrite rules, storage and API**: `GET`, `POST`, `PUT` and `DELETE /api/traffic/rewrite-rules` and `POST /api/traffic/rewrite-rules/{id}/toggle` manage rules that match a request or a response (method, host, URL, headers, body, status) and describe a rewrite (method, path and query, headers, body, status). Rules are validated on save, limited to 100 of which 50 enabled, created disabled, and stored in the new table `traffic_rewrite_rules` (migration `0005_traffic_rewrite_rules.sql`) with `matchers` and `actions` encrypted at rest. The value of an action marked `sensitive` is never returned, and an update sent without it keeps the stored one. The server compiles the enabled rules at startup and after every change and hands the snapshot to the proxy. The proxy applies them from the next entry. See `docs/traffic-rewrite-rules.md`.
Expand Down
62 changes: 54 additions & 8 deletions agent/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -387,12 +387,57 @@ func IsRunDirName(name string) bool {
return true
}

func workerSystem(proxyAddr, caCert, dataDir, runDir string) string {
// CachePrefixEnv is the opt-in environment flag enabling the worker system
// prompt cache-prefix split (P3.5 phase C). Off by default: when unset/false,
// worker system segments and DynamicBoundary are byte-identical to the legacy
// layout. Planner, mainagent, chat, and goals are unaffected.
const CachePrefixEnv = "ARTEX_CACHE_PREFIX"

func cachePrefixEnabled() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv(CachePrefixEnv))) {
case "1", "true", "on", "yes":
return true
}
return false
}

// workerSystemParts splits workerSystem at the first per-intent volatile
// segment (workerArtifactSpec(runDir)) without reordering any text:
// - staticPart = body + untrustedContentTail + workerTrafficBlock
// - dynamicHead = workerArtifactSpec(runDir) + noiseProfileBlock
//
// Custom DB prompts that reference {{.Now}} remain volatile inside staticPart.
func workerSystemParts(proxyAddr, caCert, dataDir, runDir string) (staticPart, dynamicHead string) {
body := renderSystem("worker", workerDefaultTmpl, WorkerVars{ProxyAddr: proxyAddr, DataDir: dataDir, Now: nowStr()})
// caCert is present only when the recording MITM is on, which is exactly when
// the traffic_* tools are registered — so it gates the traffic-tool note.
// Optional finding guidance is added for every role after tool resolution.
return body + untrustedContentTail(body) + workerTrafficBlock(caCert != "") + workerArtifactSpec(runDir) + noiseProfileBlock()
staticPart = body + untrustedContentTail(body) + workerTrafficBlock(caCert != "")
dynamicHead = workerArtifactSpec(runDir) + noiseProfileBlock()
return staticPart, dynamicHead
}

func workerSystem(proxyAddr, caCert, dataDir, runDir string) string {
staticPart, dynamicHead := workerSystemParts(proxyAddr, caCert, dataDir, runDir)
return staticPart + dynamicHead
}

// assembleWorkerSystem builds the worker's SystemPrompt segments and
// DynamicBoundary. When split is false (default), it delegates directly to
// deferredSystem(staticPart+dynamicTail, def). When split is true
// (ARTEX_CACHE_PREFIX=1), it emits two segments [staticPart, dynamic] with
// DynamicBoundary=1 so sibling workers in the same task share the cached static
// prefix, absorbing the leading "\n\n" separator from workerArtifactSpec so
// strings.Join(system, "\n\n") is byte-identical to the unsplit prompt.
func assembleWorkerSystem(staticPart, dynamicTail string, def DeferredInfo, split bool) (system []string, boundary int) {
if !split {
return deferredSystem(staticPart+dynamicTail, def)
}
dyn := strings.TrimPrefix(dynamicTail+def.FindingGuidance, "\n\n")
if block := actool.RenderDeferredToolsBlock(def.GlobalNames); block != "" {
dyn += "\n\n" + block
}
return []string{staticPart, dyn}, 1
}

// renderIntentTask formats the claimed intent for the worker's launch USER message:
Expand Down Expand Up @@ -524,18 +569,19 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
// inherit a parent run's background into the action reviewer.
ctx = intercept.WithReviewContext(ctx, runDir, intercept.ReviewBackground{})
overview := renderWorkerGraphOverview(tsx.graphOverviewData(), newDataEnvelope())
sysBody := workerSystem(w.proxyAddr, w.proxyCACert, w.workDir, runDir) + frameLessonsBlock(w.lessonsBlock)
staticPart, dynamicTail := workerSystemParts(w.proxyAddr, w.proxyCACert, w.workDir, runDir)
dynamicTail += frameLessonsBlock(w.lessonsBlock)
if w.wantConstraints() {
sysBody += constraintBlock(ts) // inject the operation constraints (if any) into the system prompt; the worker strictly obeys them during execution
dynamicTail += constraintBlock(ts) // inject the operation constraints (if any) into the system prompt; the worker strictly obeys them during execution
}
// intent block → intent-anchored assets block → launch instruction, appended to
// the system tail in that order (same append pattern as constraintBlock).
sysBody += renderIntentTask(intent)
dynamicTail += renderIntentTask(intent)
if as != nil {
if ids := intentAssetIDs(intent); len(ids) > 0 {
if assets, err := as.GetByIDs(ids); err == nil && len(assets) > 0 {
if b, err := json.Marshal(assets); err == nil {
sysBody += "\n\nThe target assets corresponding to this intent's asset_ids:\n" + string(b)
dynamicTail += "\n\nThe target assets corresponding to this intent's asset_ids:\n" + string(b)
}
// The assets this intent explicitly targets → automatically join the task's
// test scope (same conservative granularity as insertAssets). upsertTaskScope's
Expand All @@ -551,8 +597,8 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
}
}
}
sysBody += "\n\nStart executing the intent above: do only it, produce only facts, assets, findings, stop when done."
system, boundary := deferredSystem(sysBody, def)
dynamicTail += "\n\nStart executing the intent above: do only it, produce only facts, assets, findings, stop when done."
system, boundary := assembleWorkerSystem(staticPart, dynamicTail, def, cachePrefixEnabled())
// The task-level deadline (injected via ctx) clamps this run's wall-clock budget +
// decides the wrap-up prompt (see taskclock.go).
tc := taskClockFrom(ctx)
Expand Down
Loading
Loading