fix(openai): Work에 절대 Plan 경로를 전달한다

호출자가 이미 제공하는 working directory를 사용해 Work 입력의 Plan 경로를 절대경로로 해석한다. 잘못 추가했던 /iop 추정 alias는 제거하고 일반 workspace 호출은 그대로 통과시킨다.
This commit is contained in:
toki 2026-08-15 08:31:20 +09:00
parent 864a930b55
commit 64ab12b895
9 changed files with 57 additions and 64 deletions

View file

@ -97,7 +97,7 @@ workspace path. Before issuing caller writes, Edge validates the selector's
default lightweight PLAN and pending REVIEW seed and retains the PLAN `P1..Pn`
inventory request-locally. Selector instructions require every PLAN field to be
English ASCII, and Edge rejects a non-ASCII PLAN before issuing caller writes.
Work receives only the relative PLAN path followed by the fixed English sentence
Work receives only the absolute PLAN path resolved from the caller's existing working-directory system context, followed by the fixed English sentence
`Read it and complete the task.` and sees only ordinary caller tools. It must read
PLAN and perform and verify caller-workspace work. After a successful PLAN read and
a non-empty terminal worker report, Edge renders and validates the completed REVIEW

View file

@ -267,7 +267,7 @@ Provider-pool raw passthrough route는 위 목록을 provider request allowlist
Chat Completions의 실행 경로는 caller가 보낸 `model`의 route/provider capability로 결정한다.
- provider-pool model group route(`models[]`)는 candidate를 선택한 뒤 selected provider가 OpenAI-compatible 호출 방식을 지원하면 provider HTTP status/header/body를 Node가 열어 기존 Edge-Node tunnel로 relay하고, Edge가 caller에게 쓴다. 요청 body는 라우팅에 필요한 envelope만 읽고 `model` alias를 selected provider의 served target으로 rewrite하는 것을 기본으로 하며, provider가 지원하는 OpenAI-compatible field와 provider extension field를 보존한다.
- Provider-pool Chat과 unmarked caller-workspace의 selector/Work/Review 요청은 selected protocol profile이 선언한 출력 상한 wire spelling을 사용한다. OpenAI Chat wire는 `max_completion_tokens`, Gemini Chat wire는 `max_tokens`로 정규화한다. 형식이 bounded인 selector PLAN/REVIEW seed는 caller SDK의 큰 기본 completion limit과 분리해 최대 4096 output tokens만 허용한다. Selector provider에는 prepare 단계의 canonical `prepare(path)` 또는 pair-write 단계의 단일 `iop_write_artifact_pair(plan_content,review_content)` schema만 보여준다. Selector instruction은 모든 PLAN field를 English ASCII로 작성하도록 요구하고 Edge는 non-ASCII PLAN을 caller write 전에 거부한다. Edge는 검증된 atomic pair를 PLAN/REVIEW 두 write로 확장하고 admitted caller tool의 실제 schema(예: `bash(command)`)로 각각 encode해 caller에게 투영한다. 따라서 selector에게 두 parallel tool call 생성을 요구하지 않는다. Work provider의 전체 task prompt는 relative PLAN path와 고정 영문 `Read it and complete the task.`뿐이며 ordinary caller tools만 보인다. Work가 PLAN을 성공적으로 읽은 뒤 non-empty terminal report를 반환하면 Edge가 completed REVIEW template을 렌더·검증하고 단일 caller write로 투영한다. Work provider는 REVIEW handoff tool이나 protocol을 소유하지 않는다. 정확한 PLAN/REVIEW 접근만 artifact state로 기록하고 그 외 caller-workspace tool call은 경로 검사 없이 그대로 통과시킨다. Work/Review provider가 반환한 reserved-artifact operation은 실제 provider tool의 path alias(예: `filePath`)를 발행된 canonical path로 복원하고, 선택된 caller binding의 실제 tool 이름·argument mapping으로 정규화한 뒤 같은 codec으로 encode한다. 이 변환이 필요한 command-mode binding stage는 provider delta를 caller에게 선행 방출하지 않고 bounded stage를 수집·검증·매핑한 뒤 endpoint-native 응답으로 한 번 투영하며, 직접 투영 가능한 structured binding의 기존 progressive stream은 유지한다. Cleanup은 이미 caller-stage-only인 단일 call ID를 그대로 발행·해시하며 outer sequencer로 재투영하지 않는다. Caller continuation은 SDK가 assistant message에 추가·생략하는 content/reasoning/provider metadata가 아니라 발행된 tool-call ID·이름·arguments의 의미 해시로 issue를 결속한다. Unmarked 내부 stage가 function tools와 reasoning effort를 함께 요구하고 selected OpenAI profile의 Chat wire가 이를 지원하지 않으면, 같은 profile의 Responses operation이 두 요구를 보존할 때 내부 wire만 Responses로 전환한다. 이 내부 operation은 body와 tunnel metadata 모두 `stream=false`인 단일 buffered stage이며, provider가 거부하는 generic SDK sampling defaults인 `temperature``top_p`를 전달하지 않고 mapped effort를 generation control로 사용한다. Result decoder는 caller protocol이 아니라 selected operation을 우선하여 Responses JSON을 기존 hot-path 공통 stage shape로 복원하며, caller-visible Chat surface와 caller/agent identity로 분기하지 않는다.
- Provider-pool Chat과 unmarked caller-workspace의 selector/Work/Review 요청은 selected protocol profile이 선언한 출력 상한 wire spelling을 사용한다. OpenAI Chat wire는 `max_completion_tokens`, Gemini Chat wire는 `max_tokens`로 정규화한다. 형식이 bounded인 selector PLAN/REVIEW seed는 caller SDK의 큰 기본 completion limit과 분리해 최대 4096 output tokens만 허용한다. Selector provider에는 prepare 단계의 canonical `prepare(path)` 또는 pair-write 단계의 단일 `iop_write_artifact_pair(plan_content,review_content)` schema만 보여준다. Selector instruction은 모든 PLAN field를 English ASCII로 작성하도록 요구하고 Edge는 non-ASCII PLAN을 caller write 전에 거부한다. Edge는 검증된 atomic pair를 PLAN/REVIEW 두 write로 확장하고 admitted caller tool의 실제 schema(예: `bash(command)`)로 각각 encode해 caller에게 투영한다. 따라서 selector에게 두 parallel tool call 생성을 요구하지 않는다. Work provider의 전체 task prompt는 caller의 기존 working-directory system context에서 해석한 absolute PLAN path와 고정 영문 `Read it and complete the task.`뿐이며 ordinary caller tools만 보인다. Work가 PLAN을 성공적으로 읽은 뒤 non-empty terminal report를 반환하면 Edge가 completed REVIEW template을 렌더·검증하고 단일 caller write로 투영한다. Work provider는 REVIEW handoff tool이나 protocol을 소유하지 않는다. 정확한 PLAN/REVIEW 접근만 artifact state로 기록하고 그 외 caller-workspace tool call은 경로 검사 없이 그대로 통과시킨다. Work/Review provider가 반환한 reserved-artifact operation은 실제 provider tool의 path alias(예: `filePath`)를 발행된 canonical path로 복원하고, 선택된 caller binding의 실제 tool 이름·argument mapping으로 정규화한 뒤 같은 codec으로 encode한다. 이 변환이 필요한 command-mode binding stage는 provider delta를 caller에게 선행 방출하지 않고 bounded stage를 수집·검증·매핑한 뒤 endpoint-native 응답으로 한 번 투영하며, 직접 투영 가능한 structured binding의 기존 progressive stream은 유지한다. Cleanup은 이미 caller-stage-only인 단일 call ID를 그대로 발행·해시하며 outer sequencer로 재투영하지 않는다. Caller continuation은 SDK가 assistant message에 추가·생략하는 content/reasoning/provider metadata가 아니라 발행된 tool-call ID·이름·arguments의 의미 해시로 issue를 결속한다. Unmarked 내부 stage가 function tools와 reasoning effort를 함께 요구하고 selected OpenAI profile의 Chat wire가 이를 지원하지 않으면, 같은 profile의 Responses operation이 두 요구를 보존할 때 내부 wire만 Responses로 전환한다. 이 내부 operation은 body와 tunnel metadata 모두 `stream=false`인 단일 buffered stage이며, provider가 거부하는 generic SDK sampling defaults인 `temperature``top_p`를 전달하지 않고 mapped effort를 generation control로 사용한다. Result decoder는 caller protocol이 아니라 selected operation을 우선하여 Responses JSON을 기존 hot-path 공통 stage shape로 복원하며, caller-visible Chat surface와 caller/agent identity로 분기하지 않는다.
- selected provider가 Ollama/native provider처럼 normalized execution을 요구하면 Edge는 normalized `RunRequest` path를 사용한다. 이 경로는 OpenAI-compatible 표면을 입력/출력 compatibility layer로 제공하되, backend 호출은 normalized adapter 계약을 따른다.
- `metadata`는 경로 선택자가 아니다. Edge는 route 결정 뒤 인증 principal, usage/observability 등 IOP가 아는 bounded metadata key만 발췌한다. 이 발췌 정보는 provider body를 바꾸는 selector가 아니며, passthrough 응답 body에 IOP marker/event/envelope를 섞지 않는다.
- Chat Completions 성공 응답의 top-level `model` echo가 provider-served model이면 caller가 요청한 IOP model alias로 정규화할 수 있다. reasoning/content/tool_calls 같은 provider payload field는 보존한다.

View file

@ -208,7 +208,7 @@ Edge가 OpenAI-compatible HTTP 요청을 받아 내부 `adapter + target` 실행
| managed projection auth | `credential_plane.enabled=true` uses the fresh Control Plane projection for inbound token auth and principal route discovery. Static principal/bearer fallback is disabled. |
| managed slot route | Public model id/alias resolves to one projected route, exact slot/profile/upstream model/resource selector, and immutable revisions/generation. Unknown, cross-principal, stale, revoked, or ambiguous bindings fail closed. |
| marked preset single-request admission | An authorized fixed single-request preset compiles one service-owned admission value at request start: requested public model, canonical plan/work/review bindings resolved through managed authorization, opaque workspace capability, and absolute resource caps. Later refresh cannot mutate the admitted shape. No private binding is echoed to the caller. Compiled only after every canonical reference is verified through its catalog binding for the authenticated principal; missing, duplicate, unauthorized, dynamically selected, or option-inconsistent inputs are rejected without fallback. |
| unmarked caller-workspace light route | An unmarked `light` preset binds only admitted caller `workspace_tools`; it never accepts a raw caller path. Edge derives a phase-specific selector instruction from the locked artifact frontier. A non-parent-creating write binding first receives `prepare-only` for exactly one admitted `.iop/job/<request_id>` prepare call with PLAN/REVIEW writes prohibited; its successful receipt resumes the same selector with `pair-write` for the accepted artifact grammar. A parent-creating binding receives `pair-write` immediately. The selector provider sees only canonical `prepare(path)` or one atomic `iop_write_artifact_pair(plan_content,review_content)` schema. The selector must write every PLAN field in English ASCII; Edge rejects non-ASCII PLAN content. Edge validates and expands the pair into two independently receipted writes encoded in the admitted caller tool schema such as `bash(command)`; the selector is not required to produce parallel tool calls. Continuation issue identity covers semantic tool-call ID/name/arguments rather than SDK-decorated assistant content, reasoning, or provider metadata, while request prefix and result IDs stay independently validated. The selector instruction is the final leading Chat `system` message or final Anthropic top-level `system` text block and does not mutate the retained caller snapshot or add a public field. Work receives exactly the relative PLAN path plus `Read it and complete the task.` and only ordinary caller tools. After a successful PLAN read and a non-empty terminal worker report, Edge renders and validates the completed `P1..Pn` REVIEW handoff and projects its single caller write; Work does not manage that protocol. Exact PLAN/REVIEW access updates artifact state, while every other caller-workspace tool call passes through unchanged. Selector/Work/Review Chat bodies normalize `max_tokens`/`max_completion_tokens` to the selected profile wire; target-native values win when both aliases exist. The bounded selector PLAN/REVIEW seed is capped at 4096 output tokens independently of a caller SDK's larger completion default. When tools plus reasoning effort are not representable on the selected OpenAI Chat wire, the internal stage alone uses that profile's lossless buffered Responses operation with body/tunnel `stream=false`, omits incompatible generic SDK `temperature`/`top_p` defaults, and restores the common hot-path stage shape by selected operation rather than caller protocol. A selector upstream HTTP 400 becomes one non-retryable caller HTTP 400 `invalid_request_error`, while provider details remain private. Review reads both artifacts, successfully inspects an ordinary caller result, repairs/re-verifies in the same binding when needed, and owns the non-empty final output without rewriting REVIEW. Cleanup removes only the request `.iop/job/<request_id>` directory. Marked `single_request` presets bypass this route and retain the operator-owned Node workspace. |
| unmarked caller-workspace light route | An unmarked `light` preset binds only admitted caller `workspace_tools`; it never accepts a raw caller path. Edge derives a phase-specific selector instruction from the locked artifact frontier. A non-parent-creating write binding first receives `prepare-only` for exactly one admitted `.iop/job/<request_id>` prepare call with PLAN/REVIEW writes prohibited; its successful receipt resumes the same selector with `pair-write` for the accepted artifact grammar. A parent-creating binding receives `pair-write` immediately. The selector provider sees only canonical `prepare(path)` or one atomic `iop_write_artifact_pair(plan_content,review_content)` schema. The selector must write every PLAN field in English ASCII; Edge rejects non-ASCII PLAN content. Edge validates and expands the pair into two independently receipted writes encoded in the admitted caller tool schema such as `bash(command)`; the selector is not required to produce parallel tool calls. Continuation issue identity covers semantic tool-call ID/name/arguments rather than SDK-decorated assistant content, reasoning, or provider metadata, while request prefix and result IDs stay independently validated. The selector instruction is the final leading Chat `system` message or final Anthropic top-level `system` text block and does not mutate the retained caller snapshot or add a public field. Work receives exactly the absolute PLAN path resolved from the caller's existing working-directory system context plus `Read it and complete the task.` and only ordinary caller tools. After a successful PLAN read and a non-empty terminal worker report, Edge renders and validates the completed `P1..Pn` REVIEW handoff and projects its single caller write; Work does not manage that protocol. Exact PLAN/REVIEW access updates artifact state, while every other caller-workspace tool call passes through unchanged. Selector/Work/Review Chat bodies normalize `max_tokens`/`max_completion_tokens` to the selected profile wire; target-native values win when both aliases exist. The bounded selector PLAN/REVIEW seed is capped at 4096 output tokens independently of a caller SDK's larger completion default. When tools plus reasoning effort are not representable on the selected OpenAI Chat wire, the internal stage alone uses that profile's lossless buffered Responses operation with body/tunnel `stream=false`, omits incompatible generic SDK `temperature`/`top_p` defaults, and restores the common hot-path stage shape by selected operation rather than caller protocol. A selector upstream HTTP 400 becomes one non-retryable caller HTTP 400 `invalid_request_error`, while provider details remain private. Review reads both artifacts, successfully inspects an ordinary caller result, repairs/re-verifies in the same binding when needed, and owns the non-empty final output without rewriting REVIEW. Cleanup removes only the request `.iop/job/<request_id>` directory. Marked `single_request` presets bypass this route and retain the operator-owned Node workspace. |
| marked single-request provider normalization | Plan/Work/Review derive caller-neutral effort/tool/structured-output requirements and let the selected protocol profile choose Chat Completions or Responses. Effort exact misses fall only to the nearest declared lower grade (`max` → `xhigh` when `max` is absent). Explicit resource selectors keep exact provider-ID verification; a `default` selector leaves provider choice to the pool while model group, profile, upstream model, credential slot/revision, and tunnel path remain frozen. Both Chat and Responses results are converted into the private common Chat-shaped stage codec before Plan/Work/Review validation. Chat conversion discards only bounded standard/provider bookkeeping (`service_tier`, `system_fingerprint`, provider `timings`, choice `logprobs`, message `annotations`, null `refusal`) and rejects a non-null refusal or unknown/duplicate fields. |
| marked single-request internal templates | The admission also freezes the operator-configured effective Plan/Review Markdown templates. They are internal artifact shapes only: the Plan stage first performs a bounded read/list-only workspace inspection and requires one successful result in the same request-local conversation, then obtains a strict one-line `goal` plus bounded one-line `steps`/`verification` arrays. Edge owns the bullet formatting and renders `plan.md`; no separate analysis artifact is created. The Review template shapes the private `review.md` artifact. Callers cannot supply, name, or select a template, and template paths, contents, and digests never appear in a response, error, log, or metric label. The caller-visible Messages request/response schema is unchanged and the final text stays the model's `decision.output`. |
| marked single-request ingress | One validated and authorized Messages POST enters the separate service coordinator capability before legacy provider/caller continuation and increments `iop_anthropic_single_request_ingress_total` once. Non-streaming returns one buffered final-only message. Streaming keeps one envelope across the coordinator lifetime, exposes only fixed plan/work/review/repair text blocks plus `event: ping`, and commits one final text/error terminal. Internal reasoning/tool wire never becomes caller `tool_use`; success is acknowledged only after the complete terminal write succeeds. |
@ -420,7 +420,7 @@ sequenceDiagram
- 2026-08-14: Applied the same provider-normalization boundary to private single-request Plan/Work/Review stages. Removed pre-selection Chat operation pinning, added Chat↔Responses stage conversion and nearest-lower effort mapping, and corrected default-selector dispatch validation so the pool-selected provider is accepted without weakening explicit provider, profile, credential, target, or execution-path fences.
- 2026-08-14: Canonicalized private Chat Completions stage responses before strict Plan/Work/Review decoding. Standard OpenAI bookkeeping fields are stripped centrally, a non-null refusal remains fail-closed, and Responses/Chat now converge on the same private envelope instead of making stage codecs provider-specific.
- 2026-08-14: Added provider `timings` to the bounded Chat response bookkeeping stripped before private stage decoding, aligning the common normalizer with the existing Ornith Work codec without admitting unknown response fields.
- 2026-08-15: Reduced the unmarked light Work input to the relative PLAN path plus one fixed English sentence, limited Work to caller tools, moved completed REVIEW projection into Edge after the worker terminal report, and required English-ASCII PLAN content.
- 2026-08-15: Reduced the unmarked light Work input to the caller-workspace absolute PLAN path plus one fixed English sentence, limited Work to caller tools, moved completed REVIEW projection into Edge after the worker terminal report, and required English-ASCII PLAN content.
- 2026-08-13: Gemini-native path parsing now keeps route IDs strict while accepting the bounded URL-encoded official caller model label `Gemini 3.6 Flash`.
- 2026-08-06: Synchronized always-owned Chat/Responses typed-stall recovery, provider avoidance/fallback admission, and closed-label liveness operational evidence with the current runtime, contracts, and deterministic recovery tests.
- 2026-08-06: Added marked single-request Messages admission through the separate service coordinator capability, one unlabeled runtime ingress counter, buffered sanitized terminal acknowledgement, and deterministic real-POST compatibility evidence.

View file

@ -173,7 +173,7 @@ func TestHotPathChatMixedProviderStages(t *testing.T) {
})
tools := scriptedLightTools("openai")
history := []any{map[string]any{"role": "user", "content": "mixed provider task"}}
history := []any{map[string]any{"role": "user", "content": "Working directory: /workspace\nmixed provider task"}}
consume := func(response *httptest.ResponseRecorder, results []string) {
t.Helper()
assistant, ids, err := artifactAssistantFromResponse("openai", response.Body.Bytes())
@ -295,7 +295,7 @@ func TestHotPathChatFlushesVisibleDeltaBeforeProviderTerminal(t *testing.T) {
})
tools := scriptedLightTools("openai")
history := []any{map[string]any{"role": "user", "content": "flush before terminal"}}
history := []any{map[string]any{"role": "user", "content": "Working directory: /workspace\nflush before terminal"}}
consume := func(response *httptest.ResponseRecorder, results []string) {
t.Helper()
assistant, ids, err := artifactAssistantFromResponse("openai", response.Body.Bytes())
@ -499,7 +499,7 @@ func TestHotPathChatProviderLengthFlushesBeforeTerminalAndStopsLight(t *testing.
})
tools := scriptedLightTools("openai")
history := []any{map[string]any{"role": "user", "content": "provider length terminal"}}
history := []any{map[string]any{"role": "user", "content": "Working directory: /workspace\nprovider length terminal"}}
consume := func(response *httptest.ResponseRecorder, results []string) {
t.Helper()
assistant, ids, err := artifactAssistantFromResponse("openai", response.Body.Bytes())

View file

@ -261,7 +261,7 @@ func TestArtifactPairHandlerDisposition(t *testing.T) {
}
srv := newScriptedArtifactHandlerServer(t, service)
tools := scriptedArtifactTools(endpoint)
history := []any{map[string]any{"role": "user", "content": "write a plan"}}
history := []any{map[string]any{"role": "user", "content": "Working directory: /workspace\nwrite a plan"}}
first := serveScriptedArtifactRequest(t, srv, endpoint, scriptedArtifactRequestBody(t, endpoint, tools, history))
if first.Code != http.StatusOK || service.calls != 1 {

View file

@ -5,8 +5,6 @@ import (
"encoding/json"
"fmt"
"net/http"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
@ -598,7 +596,7 @@ func hotPathToolAllowed(tools []any, name string) bool {
}
func hotPathWorkspaceCall(kind hotPathPendingKind, paths reservedPaths, call normalizedToolCall) (workspaceOperationKind, string, bool, error) {
reserved := workspaceArtifactPathsFromToolCall(call, paths)
reserved := reservedPathsFromToolCall(call)
if len(reserved) != 1 {
return "", "", false, nil
}
@ -620,31 +618,6 @@ func hotPathWorkspaceCall(kind hotPathPendingKind, paths reservedPaths, call nor
return "", "", false, nil
}
func workspaceArtifactPathsFromToolCall(call normalizedToolCall, paths reservedPaths) []string {
set := make(map[string]struct{})
for _, path := range reservedPathsFromToolCall(call) {
set[cleanRelativePath(path)] = struct{}{}
}
addAlias := func(value string) {
normalized := filepath.ToSlash(strings.TrimSpace(value))
if strings.HasPrefix(normalized, "/iop/job/") {
normalized = "." + strings.TrimPrefix(normalized, "/")
}
cleaned := cleanRelativePath(normalized)
if cleaned == cleanRelativePath(paths.PlanPath) || cleaned == cleanRelativePath(paths.ReviewPath) {
set[cleaned] = struct{}{}
}
}
addAlias(call.Path)
collectReservedStrings(call.Arguments, addAlias)
result := make([]string, 0, len(set))
for path := range set {
result = append(result, path)
}
sort.Strings(result)
return result
}
func (s *hotPathLightStore) consumeChat(ownerEdgeID, principalRef string, rawBody []byte, lineage logicalRequestContinuationLineage, coordinator *logicalRequestCoordinator) (logicalRequestSnapshot, hotPathLightDisposition, bool, error) {
results, err := decodeChatWorkspaceResults(rawBody)
if err != nil {

View file

@ -15,6 +15,8 @@ import (
"iop/packages/go/singlerequesttemplate"
)
const scriptedAbsoluteWorkspaceTask = "system: Working directory: /workspace\nuser: immutable user task"
func TestHotPathLightLocalTransition(t *testing.T) {
for _, endpoint := range []string{"openai", "anthropic"} {
endpoint := endpoint
@ -76,24 +78,6 @@ func TestHotPathStageOrdinaryWorkspacePathPassesThrough(t *testing.T) {
}
}
func TestHotPathStageIssuedPlanSlashAliasMapsToCallerTool(t *testing.T) {
binding := mustBinding(t, fullWorkspaceAlternative("command", "bash", true), []any{openAIChatTool("bash", commandSchema())})
record := &hotPathLightRecord{
requestID: "req_stage_alias", phase: hotPathPhaseLocalActive, binding: binding,
}
coordinator := newLogicalRequestCoordinator(logicalRequestCoordinatorOptions{IDSource: func() (string, error) { return "call_public", nil }})
alias := "/" + strings.TrimPrefix(newReservedPaths(record.requestID).PlanPath, ".")
mapped, pending, err := mapHotPathStageCalls(record, normalizedStageOutput{ToolCalls: []normalizedToolCall{{
ID: "provider_read", Name: "read", Arguments: map[string]any{"filePath": alias},
}}}, hotPathPendingLocalTools, coordinator, nil)
if err != nil {
t.Fatal(err)
}
if len(mapped.ToolCalls) != 1 || mapped.ToolCalls[0].Name != "bash" || pending[mapped.ToolCalls[0].ID].payload == nil {
t.Fatalf("issued plan alias was not normalized: calls=%+v pending=%+v", mapped.ToolCalls, pending)
}
}
func TestWorkerProviderReceivesOnlyCallerTools(t *testing.T) {
callerTools := []any{openAIChatTool("run_command", commandSchema())}
tools := hotPathStageProviderTools(hotPathDispatchSnapshot{Phase: hotPathPhaseLocalActive, Tools: callerTools})
@ -150,8 +134,8 @@ func TestHotPathStageInputIsolation(t *testing.T) {
paths := newReservedPaths("req_stage_isolation")
selector := hotPathStageCorrelation{StageID: "stg_selector", ResponseID: "provider:selector.actual/1", RunID: "run-selector", ProviderID: "provider.actual", Terminal: "stop,done\"quoted\""}
local := hotPathStageCorrelation{StageID: "stg_local", ResponseID: "provider:local.actual/2", RunID: "run-local", ProviderID: "provider.actual", Terminal: "tool_calls,stop"}
localInput := buildLocalStageInput("immutable user task", paths, selector)
reviewInput := buildReviewStageInput("immutable user task", paths, selector, local)
localInput := buildLocalStageInput(scriptedAbsoluteWorkspaceTask, paths, selector)
reviewInput := buildReviewStageInput(scriptedAbsoluteWorkspaceTask, paths, selector, local)
for _, input := range []hotPathStageInput{localInput, reviewInput} {
phase := hotPathPhaseLocalActive
@ -168,7 +152,7 @@ func TestHotPathStageInputIsolation(t *testing.T) {
}
}
if input.Role == "local" {
want := paths.PlanPath + "\nRead it and complete the task."
want := "/workspace/" + paths.PlanPath + "\nRead it and complete the task."
if prompt != want {
t.Fatalf("local prompt got=%q want=%q", prompt, want)
}
@ -307,13 +291,13 @@ func TestHotPathStageInputIsolation(t *testing.T) {
for _, invalid := range invalidLogicalIDs {
selBadStage := selector
selBadStage.StageID = invalid
if p, err := buildLocalStageInput("immutable user task", paths, selBadStage).prompt(hotPathPhaseLocalActive); err == nil || p != "" {
if p, err := buildLocalStageInput(scriptedAbsoluteWorkspaceTask, paths, selBadStage).prompt(hotPathPhaseLocalActive); err == nil || p != "" {
t.Fatalf("selector StageID %q accepted: prompt=%q, err=%v", invalid, p, err)
}
selBadRun := selector
selBadRun.RunID = invalid
if p, err := buildLocalStageInput("immutable user task", paths, selBadRun).prompt(hotPathPhaseLocalActive); err == nil || p != "" {
if p, err := buildLocalStageInput(scriptedAbsoluteWorkspaceTask, paths, selBadRun).prompt(hotPathPhaseLocalActive); err == nil || p != "" {
t.Fatalf("selector RunID %q accepted: prompt=%q, err=%v", invalid, p, err)
}
}
@ -442,7 +426,7 @@ func newScriptedLightFixture(t *testing.T, endpoint string, repair bool) *script
tools := scriptedLightTools(endpoint)
return &scriptedLightFixture{
t: t, endpoint: endpoint, server: server, service: service, tools: tools,
history: []any{map[string]any{"role": "user", "content": "immutable user task"}}, repair: repair,
history: []any{map[string]any{"role": "user", "content": "Working directory: /workspace\nimmutable user task"}}, repair: repair,
}
}
@ -628,7 +612,7 @@ func assertLocalCorrelationRegression(t *testing.T, req edgeservice.ProviderPool
}
inputStr := fmt.Sprint(input)
want := newReservedPaths(req.Run.Metadata["iop_logical_request_id"]).PlanPath + "\nRead it and complete the task."
want := "/workspace/" + newReservedPaths(req.Run.Metadata["iop_logical_request_id"]).PlanPath + "\nRead it and complete the task."
if prompt != want || inputStr != want {
t.Fatalf("local prompt got=%q input=%q want=%q", prompt, inputStr, want)
}

View file

@ -3,6 +3,7 @@ package openai
import (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"unicode"
)
@ -23,7 +24,7 @@ type hotPathStageCorrelation struct {
}
// hotPathStageInput is the complete cross-stage input boundary. It contains
// only caller-owned immutable task text, issued relative paths, and committed
// only caller-owned immutable task text, issued paths, and committed
// provider correlations. Workspace contents, credentials, provider targets,
// and prior control prompts never enter this value.
type hotPathStageInput struct {
@ -113,7 +114,12 @@ func (in hotPathStageInput) prompt(phase hotPathLightPhase) (string, error) {
return "", err
}
if in.Role == "local" {
return in.Artifacts.PlanPath + "\nRead it and complete the task.", nil
root, err := callerWorkingDirectory(in.ImmutableTask)
if err != nil {
return "", err
}
planPath := filepath.ToSlash(filepath.Join(root, filepath.FromSlash(in.Artifacts.PlanPath)))
return planPath + "\nRead it and complete the task.", nil
}
var b strings.Builder
b.WriteString("User task:\n")
@ -144,6 +150,36 @@ func (in hotPathStageInput) prompt(phase hotPathLightPhase) (string, error) {
return b.String(), nil
}
func callerWorkingDirectory(task string) (string, error) {
for _, line := range strings.Split(task, "\n") {
line = strings.TrimSpace(line)
for _, role := range []string{"system:", "user:"} {
if strings.HasPrefix(line, role) {
line = strings.TrimSpace(strings.TrimPrefix(line, role))
break
}
}
for _, prefix := range []string{"Working directory:", "Current working directory:"} {
if !strings.HasPrefix(line, prefix) {
continue
}
root := filepath.Clean(strings.TrimSpace(strings.TrimPrefix(line, prefix)))
if filepath.IsAbs(root) {
return root, nil
}
}
if start := strings.Index(line, "<cwd>"); start >= 0 {
if end := strings.Index(line[start+len("<cwd>"):], "</cwd>"); end >= 0 {
root := filepath.Clean(strings.TrimSpace(line[start+len("<cwd>") : start+len("<cwd>")+end]))
if filepath.IsAbs(root) {
return root, nil
}
}
}
}
return "", fmt.Errorf("caller workspace absolute path is unavailable")
}
type correlationPromptValue struct {
StageID string `json:"stage"`
ResponseID string `json:"response"`

View file

@ -994,7 +994,7 @@ func rejectedStageSnapshot(stream bool) hotPathDispatchSnapshot {
selector := hotPathStageCorrelation{StageID: "stg-s", ResponseID: "r:s/1", RunID: "run-s", ProviderID: "p", Terminal: "t"}
return hotPathDispatchSnapshot{
Protocol: "openai", Stream: stream, StageID: "stage-r", Stage: config.ExecutionRouteStage{Model: "m"},
Input: buildLocalStageInput("immutable user task", paths, selector),
Input: buildLocalStageInput(scriptedAbsoluteWorkspaceTask, paths, selector),
Route: routeDispatch{NodeRef: "node-stage", ProviderID: "p", Adapter: "a-stage", Target: "t-stage", SessionID: "s-stage", TimeoutSec: 5, ProviderPool: true},
}
}