release: v2.1.4 isolated HTTP execute (ADR 0009)

Default execute/sse-live/stream to Supervisor worker pool; MR-01 gold;
/_runtime/*; bump CLI/wasm/ext to 2.1.4.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-10-26 18:33:33 +08:00
1 parent 58e13ee6d3
commit 3cabe53da2
56 files changed
+4957 -304

No files matched your search

+15 -14
View File
@@ -92,24 +92,25 @@ fn tool_calls_from(data: &Value) -> Value {
}
fn cancel_requested() -> bool {
if std::env::var("MARQDO_CANCEL")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false)
{
return true;
}
// Web sse-live creates an empty token file up front; only an explicit
// body ("1" / "cancelled") means the client asked to stop. Empty ≠ cancel.
// Prefer request-scoped token handle. Empty / "0" ≠ cancel (M-R1).
// When a token path is set, ignore process-global MARQDO_CANCEL so parallel
// tasks cannot cancel each other via shared env.
if let Ok(tok) = std::env::var("MARQDO_CANCEL_TOKEN") {
let path = std::path::Path::new(&tok);
if path.is_file() {
if let Ok(body) = std::fs::read_to_string(path) {
let t = body.trim();
return t == "1" || t.eq_ignore_ascii_case("cancelled");
if !tok.is_empty() {
let path = std::path::Path::new(&tok);
if path.is_file() {
if let Ok(body) = std::fs::read_to_string(path) {
let t = body.trim();
return t == "1" || t.eq_ignore_ascii_case("cancelled");
}
}
return false;
}
}
false
// Legacy single-task CLI only when no token handle is bound.
std::env::var("MARQDO_CANCEL")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false)
}
/// Mirror host `net::push_openai_delta_events`: append semantic frames to
+23 -2
View File
@@ -63,6 +63,11 @@ func ParseFrontmatter(src string) (meta map[string]string, body string) {
body = body[i+3:]
body = strings.TrimPrefix(body, "\r")
body = strings.TrimPrefix(body, "\n")
// Drop blank line(s) between closing --- and first content.
for strings.HasPrefix(body, "\n") || strings.HasPrefix(body, "\r\n") {
body = strings.TrimPrefix(body, "\r\n")
body = strings.TrimPrefix(body, "\n")
}
}
for _, line := range strings.Split(fm, "\n") {
line = strings.TrimSpace(strings.TrimSuffix(line, "\r"))
@@ -254,6 +259,10 @@ func SystemRoutes() []map[string]any {
return []map[string]any{
{"method": "GET", "path": "/_part/*", "kind": "system"},
{"method": "GET|POST", "path": "/_form/*", "kind": "system"},
{"method": "POST", "path": "/_runtime/tasks", "kind": "system"},
{"method": "GET", "path": "/_runtime/tasks/{id}", "kind": "system"},
{"method": "POST", "path": "/_runtime/tasks/{id}/cancel", "kind": "system"},
{"method": "GET", "path": "/_runtime/tasks/{id}/events", "kind": "system"},
}
}
@@ -275,8 +284,20 @@ func InspectBag(app map[string]any, declared []ArtifactFile) map[string]any {
}
}
if inv, ok := app["invoke_routes"].(map[string]any); ok {
for key := range inv {
dec = append(dec, map[string]any{"path": key, "kind": "endpoint"})
for key, v := range inv {
row := map[string]any{"path": key, "kind": "endpoint"}
if m, ok := v.(map[string]any); ok {
if c, ok := m["class"].(string); ok && c != "" {
row["class"] = c
}
if method, ok := m["method"].(string); ok && method != "" {
row["method"] = method
}
if fn, ok := m["fn"].(string); ok && fn != "" {
row["fn"] = fn
}
}
dec = append(dec, row)
}
}
if art, ok := app["artifact_routes"].(map[string]any); ok {
+48
View File
@@ -968,6 +968,54 @@ func Update(url, tableName, id string, row any, txnID ...string) (map[string]any
return map[string]any{"ok": true, "updated": float64(n)}, nil
}
// UpdateIf is a conditional update (CAS): SET row WHERE id=? AND expect_col=expect_val.
// Returns {"ok":true,"updated":N,"matched":N}. Callers treat updated==0 as conflict.
// Optional txnID routes through an open Begin transaction.
func UpdateIf(url, tableName, id string, row any, expectCol string, expectVal any, txnID ...string) (map[string]any, error) {
tn, err := ident(tableName)
if err != nil {
return nil, err
}
ecol, err := ident(expectCol)
if err != nil {
return nil, err
}
obj, ok := row.(map[string]any)
if !ok {
return nil, fmt.Errorf("row must be a map")
}
c, err := connFor(url, optTxn(txnID))
if err != nil {
return nil, err
}
var sets []string
var vals []any
for k, v := range obj {
if k == "id" {
continue
}
if _, err := ident(k); err != nil {
return nil, err
}
sets = append(sets, fmt.Sprintf(`"%s" = ?`, k))
vals = append(vals, toSQLArg(v))
}
if len(sets) == 0 {
return nil, fmt.Errorf("nothing to update")
}
vals = append(vals, id, toSQLArg(expectVal))
sqlStmt := fmt.Sprintf(
`UPDATE "%s" SET %s WHERE "id" = ? AND "%s" = ?`,
tn, strings.Join(sets, ", "), ecol,
)
res, err := c.Exec(sqlStmt, vals...)
if err != nil {
return nil, err
}
n, _ := res.RowsAffected()
return map[string]any{"ok": true, "updated": float64(n), "matched": float64(n)}, nil
}
// Delete removes a row by id. Returns {"ok":true,"deleted":N}.
// Optional txnID routes through an open Begin transaction.
func Delete(url, tableName, id string, txnID ...string) (map[string]any, error) {
+18
View File
@@ -100,6 +100,24 @@ func TestInitInsertSelectGet(t *testing.T) {
}
}
func TestUpdateIfCAS(t *testing.T) {
url := setupArticles(t)
ok, err := db.UpdateIf(url, "articles", "1", map[string]any{"title": "CAS"}, "title", "Alpha")
if err != nil {
t.Fatal(err)
}
if ok["updated"] != float64(1) {
t.Fatalf("cas hit=%v", ok)
}
miss, err := db.UpdateIf(url, "articles", "1", map[string]any{"title": "Nope"}, "title", "Alpha")
if err != nil {
t.Fatal(err)
}
if miss["updated"] != float64(0) {
t.Fatalf("cas miss should be 0, got %v", miss)
}
}
func TestUpdateDelete(t *testing.T) {
url := setupArticles(t)
+1
View File
@@ -239,6 +239,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
st.mountGalleryRoutes(mux)
st.mountProxyRoutes(mux)
st.mountInvokeRoutes(mux)
st.mountRuntimeRoutes(mux)
st.mountArtifactRoutes(mux)
st.mountAuthRoutes(mux)
+393 -106
View File
@@ -1,24 +1,43 @@
package httpx
import (
"bufio"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/marqdo/marqdo/plugins/web/internal/plugin"
)
// legacySSEBridgeMu serializes the process-global MARQDO_EVENT_FORWARD /
// MARQDO_CANCEL_TOKEN bridge for the legacy_serial path only. Isolated execute
// never acquires this lock (ADR 0009).
var legacySSEBridgeMu sync.Mutex
// legacySSEBridgeActive is 1 while a holder has mutated process env for the bridge.
var legacySSEBridgeActive atomic.Int32
func tryAcquireLegacySSEBridge() bool {
return legacySSEBridgeMu.TryLock()
}
func releaseLegacySSEBridge() {
legacySSEBridgeActive.Store(0)
legacySSEBridgeMu.Unlock()
}
type invokeRoute struct {
Method string
FnPath string
BodyMode string
ReturnMode string
Class string
}
func parseInvokeRoute(v any) invokeRoute {
@@ -30,11 +49,16 @@ func parseInvokeRoute(v any) invokeRoute {
if fn == "" {
fn = strOpt(m, "function", "")
}
class := strings.ToLower(strOpt(m, "class", ""))
if class == "" {
class = strings.ToLower(strOpt(m, "类别", ""))
}
return invokeRoute{
Method: method,
FnPath: fn,
BodyMode: body,
ReturnMode: ret,
Class: class,
}
}
@@ -106,7 +130,6 @@ func (st *state) handleInvoke(w http.ResponseWriter, r *http.Request, route invo
}
}
// Bind common auth / client headers for OpenAI-compatible and API-key surfaces.
if auth := strings.TrimSpace(r.Header.Get("Authorization")); auth != "" {
if _, exists := payload["authorization"]; !exists {
payload["authorization"] = auth
@@ -120,19 +143,41 @@ func (st *state) handleInvoke(w http.ResponseWriter, r *http.Request, route invo
args := invokeArgsFromPayload(payload)
// M02: live SSE — stream host_stream_publish events while CallLibPath runs.
// return=sse-live|sse_live uses MARQDO_EVENT_FORWARD NDJSON bridge (request-local).
// Also auto-upgrade json routes when the OpenAI-compatible body asks stream:true
// so token deltas flush before the lib call returns (Q06 / workbench).
liveSSE := route.ReturnMode == "sse-live" || route.ReturnMode == "sse_live"
if !liveSSE && payloadWantsStream(payload) {
liveSSE = true
}
if liveSSE {
st.handleInvokeLiveSSE(w, r, route, args)
return
}
class := resolveInvokeClass(route, liveSSE)
switch class {
case "execute":
st.handleInvokeIsolated(w, r, route, args, liveSSE)
return
case "short", "read", "control":
st.handleInvokeParent(w, r, route, args)
return
default:
// legacy_serial: parent CallLibPath (ADR 0008). Never isolate undeclared non-stream.
st.handleInvokeParent(w, r, route, args)
}
}
func resolveInvokeClass(route invokeRoute, liveSSE bool) string {
c := strings.ToLower(strings.TrimSpace(route.Class))
switch c {
case "execute", "short", "read", "control":
return c
case "legacy", "legacy_serial":
return "legacy_serial"
}
if liveSSE {
return "execute"
}
return "legacy_serial"
}
func (st *state) handleInvokeParent(w http.ResponseWriter, r *http.Request, route invokeRoute, args map[string]any) {
_ = r
value, err := plugin.CallLibPath(route.FnPath, args)
if err != nil {
code := http.StatusInternalServerError
@@ -156,8 +201,6 @@ func (st *state) handleInvoke(w http.ResponseWriter, r *http.Request, route invo
return
}
// OpenAI-compatible handlers may return `{sse: "..."}` to force event-stream
// even when the route's declared return mode is json.
if m, ok := value.(map[string]any); ok {
if s, ok := m["sse"].(string); ok && strings.TrimSpace(s) != "" {
writeSSE(w, m)
@@ -200,41 +243,88 @@ func (st *state) handleInvoke(w http.ResponseWriter, r *http.Request, route invo
}
}
// handleInvokeLiveSSE streams RuntimeEvent-shaped lines while the lib call runs.
// Client disconnect sets MARQDO_CANCEL + cancel token file so the llm plugin can stop.
func (st *state) handleInvokeLiveSSE(w http.ResponseWriter, r *http.Request, route invokeRoute, args map[string]any) {
dir := os.TempDir()
fwd, err := os.CreateTemp(dir, "mq-evt-*.ndjson")
// handleInvokeIsolated runs execute-class invokes on a Supervisor worker (no
// parent CallLibPath, no process Setenv, no legacySSEBridgeMu).
func (st *state) handleInvokeIsolated(w http.ResponseWriter, r *http.Request, route invokeRoute, args map[string]any, liveSSE bool) {
taskID := fmt.Sprintf("exec_%d", time.Now().UnixNano())
adm, err := runtimeQuery("admit", map[string]any{
"task_id": taskID,
"idempotency_key": taskID,
"class": "execute",
"payload": map[string]any{"fn": route.FnPath},
})
if err != nil {
jsonErr(w, http.StatusInternalServerError, fmt.Sprintf("event forward: %v", err))
jsonErr(w, http.StatusInternalServerError, fmt.Sprintf("admit: %v", err))
return
}
fwdPath := fwd.Name()
_ = fwd.Close()
defer os.Remove(fwdPath)
prev := os.Getenv("MARQDO_EVENT_FORWARD")
_ = os.Setenv("MARQDO_EVENT_FORWARD", fwdPath)
cancelFile, cancelErr := os.CreateTemp(dir, "mq-cancel-*.tok")
cancelPath := ""
if cancelErr == nil {
cancelPath = cancelFile.Name()
_ = cancelFile.Close()
_ = os.Setenv("MARQDO_CANCEL_TOKEN", cancelPath)
if ok, _ := adm["ok"].(bool); !ok {
status := http.StatusServiceUnavailable
if s, ok := adm["status"].(float64); ok && s >= 400 {
status = int(s)
}
w.Header().Set("Retry-After", "2")
jsonErr(w, status, fmt.Sprint(adm["error"]))
return
}
defer func() {
if prev == "" {
_ = os.Unsetenv("MARQDO_EVENT_FORWARD")
} else {
_ = os.Setenv("MARQDO_EVENT_FORWARD", prev)
}
_ = os.Unsetenv("MARQDO_CANCEL_TOKEN")
_ = os.Unsetenv("MARQDO_CANCEL")
if cancelPath != "" {
_ = os.Remove(cancelPath)
}
}()
cancelTok, _ := adm["cancel_token"].(string)
eventPath, _ := adm["event_path"].(string)
entryModule, fsRoot, err := resolveSiteEntry(st)
if err != nil {
jsonErr(w, http.StatusInternalServerError, err.Error())
return
}
argsFile, err := materializeArgsJSON(args)
if err != nil {
jsonErr(w, http.StatusInternalServerError, fmt.Sprintf("args: %v", err))
return
}
defer os.Remove(argsFile)
disp, err := runtimeQuery("dispatch", map[string]any{
"task_id": taskID,
"entry": map[string]any{
"module": entryModule,
"function": route.FnPath,
},
"fs_root": fsRoot,
"args_json": argsFile,
})
if err != nil {
_, _ = runtimeQuery("cancel", map[string]any{"task_id": taskID})
jsonErr(w, http.StatusInternalServerError, fmt.Sprintf("dispatch: %v", err))
return
}
if ok, _ := disp["ok"].(bool); !ok {
status := http.StatusTooManyRequests
if s, ok := disp["status"].(float64); ok && s >= 400 {
status = int(s)
}
if ra, ok := disp["Retry-After"]; ok {
w.Header().Set("Retry-After", fmt.Sprint(ra))
} else {
w.Header().Set("Retry-After", "2")
}
jsonErr(w, status, fmt.Sprint(disp["error"]))
return
}
if ep, ok := disp["event_path"].(string); ok && ep != "" {
eventPath = ep
}
if tok, ok := disp["cancel_token"].(string); ok && tok != "" {
cancelTok = tok
}
emitResult, _ := disp["emit_result"].(string)
if liveSSE {
st.streamIsolatedSSE(w, r, route, taskID, eventPath, cancelTok, emitResult)
return
}
st.waitIsolatedJSON(w, r, route, taskID, eventPath, cancelTok, emitResult)
}
func (st *state) streamIsolatedSSE(w http.ResponseWriter, r *http.Request, route invokeRoute, taskID, eventPath, cancelTok, emitResult string) {
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
@@ -255,81 +345,248 @@ func (st *state) handleInvokeLiveSSE(w http.ResponseWriter, r *http.Request, rou
"schema": "RuntimeEventV1",
"schema_version": 1,
"type": "run.started",
"payload": map[string]any{"fn": route.FnPath, "bridge": "sse-live"},
"payload": map[string]any{
"fn": route.FnPath,
"bridge": "isolated",
"task_id": taskID,
},
})
type callResult struct {
value any
err error
}
done := make(chan callResult, 1)
go func() {
v, e := plugin.CallLibPath(route.FnPath, args)
if e != nil && strings.Contains(e.Error(), "interpreter busy") {
// Another invoke still holds the lock — surface as failed run, not hang.
e = fmt.Errorf("interpreter busy: try again shortly")
}
done <- callResult{value: v, err: e}
}()
var mu sync.Mutex
offset := int64(0)
carry := ""
seq := uint64(1)
poll := time.NewTicker(25 * time.Millisecond)
defer poll.Stop()
ctx := r.Context()
for {
select {
case <-ctx.Done():
// Propagate cancel to in-flight LLM/plugin via token file + env.
_ = os.Setenv("MARQDO_CANCEL", "1")
if cancelPath != "" {
_ = os.WriteFile(cancelPath, []byte("cancelled"), 0o600)
finish := func(clientGone bool) {
offset, carry = drainForwardCarry(eventPath, offset, carry, func(line string) {
seq++
writeEvent(normalizeLiveSSELine(seq, line))
})
if !clientGone {
result := readEmitResult(emitResult)
if result == nil {
if g, err := runtimeQuery("get", map[string]any{"task_id": taskID}); err == nil {
if t, ok := g["task"].(map[string]any); ok {
result = t["result"]
}
}
}
writeEvent(map[string]any{
"schema": "RuntimeEventV1", "schema_version": 1, "type": "run.interrupted",
"payload": map[string]any{"reason": "client_disconnect", "cancel_propagated": cancelPath != ""},
"schema": "RuntimeEventV1", "schema_version": 1, "type": "run.completed",
"payload": map[string]any{"result": result, "task_id": taskID},
})
return
case res := <-done:
// Drain remaining forward lines once.
mu.Lock()
offset = drainForward(fwdPath, offset, func(line string) {
seq++
writeEvent(normalizeLiveSSELine(seq, line))
})
mu.Unlock()
if res.err != nil {
writeEvent(map[string]any{
"schema": "RuntimeEventV1", "schema_version": 1, "type": "run.failed",
"payload": map[string]any{"error": res.err.Error()},
})
} else {
writeEvent(map[string]any{
"schema": "RuntimeEventV1", "schema_version": 1, "type": "run.completed",
"payload": map[string]any{"result": res.value},
})
}
_, _ = io.WriteString(w, "data: [DONE]\n\n")
if flusher != nil {
flusher.Flush()
}
}
}
for {
select {
case <-ctx.Done():
_, _ = runtimeQuery("cancel", map[string]any{"task_id": taskID})
_ = writeCancelToken(cancelTok)
writeEvent(map[string]any{
"schema": "RuntimeEventV1", "schema_version": 1, "type": "run.interrupted",
"payload": map[string]any{
"reason": "client_disconnect",
"cancel_propagated": cancelTok != "",
"status": "stopping",
"task_id": taskID,
},
})
// Brief wait so worker can notice cancel and flush.
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
if workerDone(taskID, emitResult) {
break
}
time.Sleep(50 * time.Millisecond)
}
finish(true)
return
case <-poll.C:
mu.Lock()
offset = drainForward(fwdPath, offset, func(line string) {
offset, carry = drainForwardCarry(eventPath, offset, carry, func(line string) {
seq++
writeEvent(normalizeLiveSSELine(seq, line))
})
mu.Unlock()
if workerDone(taskID, emitResult) {
finish(false)
return
}
}
}
}
// normalizeLiveSSELine maps Marqdo EventBus frames (LLM delta/text, workbench
// envelopes) onto RuntimeEventV1 so chat UIs see message.delta.payload.delta
// while tokens still arrive before run.completed.
func (st *state) waitIsolatedJSON(w http.ResponseWriter, r *http.Request, route invokeRoute, taskID, eventPath, cancelTok, emitResult string) {
_ = eventPath
poll := time.NewTicker(25 * time.Millisecond)
defer poll.Stop()
ctx := r.Context()
for {
select {
case <-ctx.Done():
_, _ = runtimeQuery("cancel", map[string]any{"task_id": taskID})
_ = writeCancelToken(cancelTok)
jsonErr(w, http.StatusRequestTimeout, "client disconnected")
return
case <-poll.C:
if !workerDone(taskID, emitResult) {
continue
}
value := readEmitResult(emitResult)
if value == nil {
jsonErr(w, http.StatusInternalServerError, "worker produced no result")
return
}
if m, ok := value.(map[string]any); ok {
if s, ok := m["sse"].(string); ok && strings.TrimSpace(s) != "" {
writeSSE(w, m)
return
}
}
switch route.ReturnMode {
case "text", "html", "text/html":
text := fmt.Sprint(value)
if s, ok := value.(string); ok {
text = s
}
ct := "text/plain; charset=utf-8"
if route.ReturnMode == "html" || route.ReturnMode == "text/html" {
ct = "text/html; charset=utf-8"
}
w.Header().Set("Content-Type", ct)
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, text)
case "status":
w.WriteHeader(http.StatusNoContent)
default:
code, body, err := jsonWrapInvokeValue(value)
if err != nil {
jsonErr(w, code, err.Error())
return
}
writeJSON(w, code, body)
}
return
}
}
}
func workerDone(taskID, emitResult string) bool {
if emitResult != "" {
if st, err := os.Stat(emitResult); err == nil && st.Size() > 0 {
return true
}
}
// Sibling of event file written by Supervisor even if emit_result was omitted.
if taskID != "" {
if dir := os.Getenv("MARQDO_RUNTIME_DIR"); dir != "" {
p := filepath.Join(dir, "events", taskID+".result.json")
if st, err := os.Stat(p); err == nil && st.Size() > 0 {
return true
}
}
}
g, err := runtimeQuery("get", map[string]any{"task_id": taskID})
if err != nil {
return false
}
if _, ok := g["exit_code"]; ok {
return true
}
if t, ok := g["task"].(map[string]any); ok {
switch fmt.Sprint(t["state"]) {
case "succeeded", "failed", "cancelled", "interrupted":
return true
}
}
return false
}
func readEmitResult(path string) any {
if path == "" {
return nil
}
b, err := os.ReadFile(path)
if err != nil || len(b) == 0 {
return nil
}
var v any
if err := json.Unmarshal(b, &v); err != nil {
return string(b)
}
return v
}
func materializeArgsJSON(args map[string]any) (string, error) {
f, err := os.CreateTemp("", "mq-args-*.json")
if err != nil {
return "", err
}
path := f.Name()
enc := json.NewEncoder(f)
if err := enc.Encode(args); err != nil {
_ = f.Close()
_ = os.Remove(path)
return "", err
}
if err := f.Close(); err != nil {
_ = os.Remove(path)
return "", err
}
return path, nil
}
func resolveSiteEntry(st *state) (module string, fsRoot string, err error) {
fsRoot = st.entryDir
if raw, qerr := plugin.Query("entry_dir", "{}"); qerr == nil {
var s string
if json.Unmarshal([]byte(raw), &s) == nil && s != "" {
fsRoot = s
}
}
if raw, qerr := plugin.Query("entry_path", "{}"); qerr == nil {
var s string
if json.Unmarshal([]byte(raw), &s) == nil && s != "" {
module = s
}
}
if module == "" {
// Fallback: common serve entry names under fs_root.
for _, name := range []string{"serve.mq.md", "index.mq.md", "main.mq.md"} {
p := filepath.Join(fsRoot, name)
if st, e := os.Stat(p); e == nil && !st.IsDir() {
module = p
break
}
}
}
if module == "" {
return "", "", fmt.Errorf("isolated execute: cannot resolve site entry module")
}
if !filepath.IsAbs(module) {
abs, aerr := filepath.Abs(module)
if aerr == nil {
module = abs
}
}
if fsRoot == "" {
fsRoot = filepath.Dir(module)
}
if !filepath.IsAbs(fsRoot) {
abs, aerr := filepath.Abs(fsRoot)
if aerr == nil {
fsRoot = abs
}
}
return module, fsRoot, nil
}
// normalizeLiveSSELine maps Marqdo EventBus frames onto RuntimeEventV1.
func normalizeLiveSSELine(seq uint64, line string) map[string]any {
base := map[string]any{
"schema": "RuntimeEventV1", "schema_version": 1, "seq": seq,
@@ -340,7 +597,6 @@ func normalizeLiveSSELine(seq uint64, line string) map[string]any {
base["payload"] = map[string]any{"raw": line}
return base
}
// Already workbench-shaped.
if t, _ := obj["type"].(string); t == "message.delta" || t == "turn.started" || t == "model.resolved" || t == "usage.updated" || t == "turn.completed" || t == "turn.failed" {
for k, v := range obj {
base[k] = v
@@ -348,15 +604,12 @@ func normalizeLiveSSELine(seq uint64, line string) map[string]any {
base["seq"] = seq
return base
}
// LLM plugin / net SSE: {type:delta|plan|reasoning, text:...}
if t, _ := obj["type"].(string); t == "delta" || t == "plan" || t == "reasoning" {
text, _ := obj["text"].(string)
base["type"] = "message.delta"
base["payload"] = map[string]any{"delta": text, "kind": t}
return base
}
// Plan process cards — keep as message.delta for back-compat, but never
// promote `result` into payload.delta (that caused full-answer duplication).
if t, _ := obj["type"].(string); t == "decompose" || t == "decision" || t == "await" || t == "round" || t == "done" || t == "tool_start" || t == "tool_end" || t == "plan_act" {
base["type"] = "message.delta"
base["payload"] = obj
@@ -373,23 +626,57 @@ func normalizeLiveSSELine(seq uint64, line string) map[string]any {
}
func drainForward(path string, offset int64, onLine func(string)) int64 {
off, _ := drainForwardCarry(path, offset, "", onLine)
return off
}
const drainForwardMaxLine = 1024 * 1024
func drainForwardCarry(path string, offset int64, carry string, onLine func(string)) (int64, string) {
f, err := os.Open(path)
if err != nil {
return offset
return offset, carry
}
defer f.Close()
if _, err := f.Seek(offset, io.SeekStart); err != nil {
return offset
return offset, carry
}
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
offset += int64(len(sc.Bytes()) + 1)
chunk, err := io.ReadAll(io.LimitReader(f, drainForwardMaxLine+1))
if err != nil && err != io.EOF {
onLine(fmt.Sprintf(`{"type":"protocol.error","error":%q}`, err.Error()))
return offset, carry
}
if len(chunk) == 0 {
return offset, carry
}
offset += int64(len(chunk))
buf := carry + string(chunk)
for {
i := strings.IndexByte(buf, '\n')
if i < 0 {
if len(buf) > drainForwardMaxLine {
onLine(`{"type":"protocol.error","error":"ndjson line exceeds 1MiB"}`)
return offset, ""
}
return offset, buf
}
lineBytes := buf[:i]
line := strings.TrimSpace(strings.TrimSuffix(lineBytes, "\r"))
buf = buf[i+1:]
if line == "" {
continue
}
onLine(line)
}
return offset
}
func legacySSEBridgeSnapshot() (active bool, forward string, cancelTok string) {
return legacySSEBridgeActive.Load() != 0, os.Getenv("MARQDO_EVENT_FORWARD"), os.Getenv("MARQDO_CANCEL_TOKEN")
}
func writeCancelToken(path string) error {
if path == "" {
return nil
}
return os.WriteFile(path, []byte("cancelled"), 0o600)
}
@@ -0,0 +1,207 @@
package httpx
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/marqdo/marqdo/plugins/web/internal/plugin"
)
// System runtime control routes (M-R3 / M-R4). Cancel and event replay do not
// enter the Marqdo interpreter lock.
func (st *state) mountRuntimeRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST /_runtime/tasks", st.handleRuntimeAdmit)
mux.HandleFunc("GET /_runtime/tasks/{id}", st.handleRuntimeGet)
mux.HandleFunc("POST /_runtime/tasks/{id}/cancel", st.handleRuntimeCancel)
mux.HandleFunc("GET /_runtime/tasks/{id}/events", st.handleRuntimeEvents)
}
func runtimeQuery(op string, extra map[string]any) (map[string]any, error) {
payload := map[string]any{"op": op}
for k, v := range extra {
payload[k] = v
}
raw, err := json.Marshal(payload)
if err != nil {
return nil, err
}
out, err := plugin.Query("runtime", string(raw))
if err != nil {
return nil, err
}
var m map[string]any
if err := json.Unmarshal([]byte(out), &m); err != nil {
return nil, err
}
return m, nil
}
func (st *state) handleRuntimeAdmit(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
jsonErr(w, http.StatusBadRequest, err.Error())
return
}
var req map[string]any
if len(body) > 0 {
if err := json.Unmarshal(body, &req); err != nil {
jsonErr(w, http.StatusBadRequest, fmt.Sprintf("json: %v", err))
return
}
}
if req == nil {
req = map[string]any{}
}
taskID, _ := req["task_id"].(string)
if taskID == "" {
taskID = fmt.Sprintf("task_%d", time.Now().UnixNano())
req["task_id"] = taskID
}
if _, ok := req["idempotency_key"]; !ok {
req["idempotency_key"] = taskID
}
if _, ok := req["class"]; !ok {
req["class"] = "execute"
}
m, err := runtimeQuery("admit", req)
if err != nil {
if strings.Contains(err.Error(), "conflict") || strings.Contains(fmt.Sprint(m["error"]), "conflict") {
jsonErr(w, http.StatusConflict, err.Error())
return
}
jsonErr(w, http.StatusInternalServerError, err.Error())
return
}
if ok, _ := m["ok"].(bool); !ok {
jsonErr(w, http.StatusConflict, fmt.Sprint(m["error"]))
return
}
w.Header().Set("Location", "/_runtime/tasks/"+taskID)
writeJSON(w, http.StatusAccepted, m)
}
func (st *state) handleRuntimeGet(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
m, err := runtimeQuery("get", map[string]any{"task_id": id})
if err != nil {
jsonErr(w, http.StatusInternalServerError, err.Error())
return
}
if st, _ := m["status"].(float64); st == 404 || fmt.Sprint(m["error"]) == "not_found" {
jsonErr(w, http.StatusNotFound, "task not found")
return
}
writeJSON(w, http.StatusOK, m)
}
func (st *state) handleRuntimeCancel(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
m, err := runtimeQuery("cancel", map[string]any{"task_id": id})
if err != nil {
jsonErr(w, http.StatusInternalServerError, err.Error())
return
}
if st, _ := m["status"].(float64); st == 404 || fmt.Sprint(m["error"]) == "not_found" {
jsonErr(w, http.StatusNotFound, "task not found")
return
}
writeJSON(w, http.StatusOK, m)
}
func (st *state) handleRuntimeEvents(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
after := int64(0)
if s := r.URL.Query().Get("after_seq"); s != "" {
fmt.Sscanf(s, "%d", &after)
}
if last := strings.TrimSpace(r.Header.Get("Last-Event-ID")); last != "" {
// Accept "task:seq" or bare seq.
if i := strings.LastIndexByte(last, ':'); i >= 0 {
fmt.Sscanf(last[i+1:], "%d", &after)
} else {
fmt.Sscanf(last, "%d", &after)
}
}
wantSSE := strings.Contains(r.Header.Get("Accept"), "text/event-stream") ||
r.URL.Query().Get("stream") == "1"
if !wantSSE {
m, err := runtimeQuery("events", map[string]any{"task_id": id, "after_seq": after})
if err != nil {
jsonErr(w, http.StatusInternalServerError, err.Error())
return
}
if st, _ := m["status"].(float64); st == 404 || fmt.Sprint(m["error"]) == "not_found" {
jsonErr(w, http.StatusNotFound, "task not found")
return
}
writeJSON(w, http.StatusOK, m)
return
}
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(http.StatusOK)
flusher, _ := w.(http.Flusher)
cursor := after
ticker := time.NewTicker(25 * time.Millisecond)
defer ticker.Stop()
heartbeat := time.NewTicker(15 * time.Second)
defer heartbeat.Stop()
ctx := r.Context()
for {
select {
case <-ctx.Done():
return
case <-heartbeat.C:
_, _ = io.WriteString(w, ": ping\n\n")
if flusher != nil {
flusher.Flush()
}
case <-ticker.C:
m, err := runtimeQuery("events", map[string]any{"task_id": id, "after_seq": cursor})
if err != nil {
continue
}
if st, _ := m["status"].(float64); st == 404 {
_, _ = io.WriteString(w, "event: error\ndata: {\"error\":\"not_found\"}\n\n")
if flusher != nil {
flusher.Flush()
}
return
}
evs, _ := m["events"].([]any)
for _, raw := range evs {
b, err := json.Marshal(raw)
if err != nil {
continue
}
var obj map[string]any
_ = json.Unmarshal(b, &obj)
eid := ""
if s, ok := obj["event_id"].(string); ok {
eid = s
}
if seq, ok := obj["seq"].(float64); ok {
cursor = int64(seq)
}
etype, _ := obj["type"].(string)
if etype == "" {
etype = "message"
}
if eid != "" {
_, _ = io.WriteString(w, "id: "+eid+"\n")
}
_, _ = io.WriteString(w, "event: "+etype+"\ndata: "+string(b)+"\n\n")
if flusher != nil {
flusher.Flush()
}
}
}
}
}
@@ -0,0 +1,14 @@
package httpx
import (
"testing"
)
func TestSystemRuntimeRoutesListed(t *testing.T) {
// Compile-time presence: handlers must be addressable.
var st state
_ = st.handleRuntimeAdmit
_ = st.handleRuntimeCancel
_ = st.handleRuntimeEvents
_ = st.handleRuntimeGet
}
@@ -0,0 +1,150 @@
package httpx
import (
"os"
"path/filepath"
"sync"
"testing"
"time"
)
// M-R0: second stream must fail before rewriting A's forward/cancel env.
func TestLegacySSEBridgeSingleFlight(t *testing.T) {
if !tryAcquireLegacySSEBridge() {
t.Fatal("expected first acquire to succeed")
}
fwdA := filepath.Join(t.TempDir(), "a.ndjson")
tokA := filepath.Join(t.TempDir(), "a.tok")
if err := os.WriteFile(fwdA, nil, 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(tokA, nil, 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("MARQDO_EVENT_FORWARD", fwdA)
t.Setenv("MARQDO_CANCEL_TOKEN", tokA)
legacySSEBridgeActive.Store(1)
if tryAcquireLegacySSEBridge() {
releaseLegacySSEBridge()
t.Fatal("second acquire must fail while bridge held")
}
active, fwd, tok := legacySSEBridgeSnapshot()
if !active {
t.Fatal("bridge should remain active for holder A")
}
if fwd != fwdA || tok != tokA {
t.Fatalf("rejected second stream rewrote env: fwd=%q tok=%q", fwd, tok)
}
releaseLegacySSEBridge()
if tryAcquireLegacySSEBridge() {
releaseLegacySSEBridge()
} else {
t.Fatal("bridge should be free after release")
}
}
// M-R0: disconnect marks cancel; token file must not be deleted while holder waits.
func TestCancelTokenSurvivesUntilHolderExits(t *testing.T) {
dir := t.TempDir()
tok := filepath.Join(dir, "cancel.tok")
if err := os.WriteFile(tok, nil, 0o600); err != nil {
t.Fatal(err)
}
if err := writeCancelToken(tok); err != nil {
t.Fatal(err)
}
body, err := os.ReadFile(tok)
if err != nil {
t.Fatalf("token must still exist after cancel mark: %v", err)
}
if string(body) != "cancelled" {
t.Fatalf("body=%q", body)
}
}
func TestDrainForwardCarryHalfFrames(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "evt.ndjson")
if err := os.WriteFile(path, []byte(`{"t":"部`), 0o600); err != nil {
t.Fatal(err)
}
var lines []string
off, carry := drainForwardCarry(path, 0, "", func(line string) {
lines = append(lines, line)
})
if len(lines) != 0 {
t.Fatalf("incomplete UTF-8 frame must stay in carry, got %#v", lines)
}
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
t.Fatal(err)
}
if _, err := f.WriteString("分\"}\n{\"t\":\"ok\"}\n"); err != nil {
t.Fatal(err)
}
_ = f.Close()
off, carry = drainForwardCarry(path, off, carry, func(line string) {
lines = append(lines, line)
})
if len(lines) != 2 {
t.Fatalf("got %d lines %#v carry=%q off=%d", len(lines), lines, carry, off)
}
if carry != "" {
t.Fatalf("carry should be empty, got %q", carry)
}
}
func TestDrainForwardCarryCRLFAndSplit(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "evt.ndjson")
part1 := []byte("{\"a\":1}\r\n{\"b\":")
if err := os.WriteFile(path, part1, 0o600); err != nil {
t.Fatal(err)
}
var lines []string
off, carry := drainForwardCarry(path, 0, "", func(line string) {
lines = append(lines, line)
})
if len(lines) != 1 || lines[0] != `{"a":1}` {
t.Fatalf("first frame %#v", lines)
}
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
t.Fatal(err)
}
if _, err := f.WriteString("2}\n"); err != nil {
t.Fatal(err)
}
_ = f.Close()
_, carry = drainForwardCarry(path, off, carry, func(line string) {
lines = append(lines, line)
})
if len(lines) != 2 || lines[1] != `{"b":2}` {
t.Fatalf("split frame %#v carry=%q", lines, carry)
}
}
func TestLegacySSEBridgeConcurrentReject(t *testing.T) {
var wg sync.WaitGroup
acquired := 0
var mu sync.Mutex
for i := 0; i < 8; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if tryAcquireLegacySSEBridge() {
mu.Lock()
acquired++
mu.Unlock()
time.Sleep(20 * time.Millisecond)
releaseLegacySSEBridge()
}
}()
}
wg.Wait()
if acquired < 1 {
t.Fatal("expected at least one acquirer")
}
}
+14 -5
View File
@@ -16,9 +16,10 @@ type Options struct {
Fn string
Body string
Return string
Class string
}
// RoutesFromTable normalizes `|路径|方法|函数|正文|返回|` into invoke_routes map keys.
// RoutesFromTable normalizes `|路径|方法|函数|正文|返回|类别|` into invoke_routes map keys.
func RoutesFromTable(tableV any) map[string]any {
rows, _ := table.AsRows(tableV).([]any)
out := map[string]any{}
@@ -47,7 +48,8 @@ func RoutesFromTable(tableV any) map[string]any {
if ret == "" {
ret = "json"
}
out[path] = routeEntry(method, fnPath, body, ret)
class := strings.ToLower(strings.TrimSpace(col(m, "类别", "class", "Class")))
out[path] = routeEntry(method, fnPath, body, ret, class)
}
return out
}
@@ -78,12 +80,13 @@ func Register(appBag map[string]any, opts Options) (map[string]any, error) {
if ret == "" {
ret = "json"
}
class := strings.ToLower(strings.TrimSpace(opts.Class))
out := clone(appBag)
routes := map[string]any{}
if r, ok := out["invoke_routes"].(map[string]any); ok {
routes = clone(r)
}
routes[key] = routeEntry(method, fnPath, body, ret)
routes[key] = routeEntry(method, fnPath, body, ret, class)
out["invoke_routes"] = routes
return out, nil
}
@@ -101,22 +104,28 @@ func OptionsFromArgs(args map[string]any) (Options, error) {
method, _ := argStr(args, "method", "方法")
body, _ := argStr(args, "body", "正文")
ret, _ := argStr(args, "return", "返回")
class, _ := argStr(args, "class", "类别")
return Options{
Path: path,
Method: method,
Fn: fnPath,
Body: body,
Return: ret,
Class: class,
}, nil
}
func routeEntry(method, fnPath, body, ret string) map[string]any {
return map[string]any{
func routeEntry(method, fnPath, body, ret, class string) map[string]any {
m := map[string]any{
"method": method,
"fn": fnPath,
"body": body,
"return": ret,
}
if class != "" {
m["class"] = class
}
return m
}
func col(m map[string]any, keys ...string) string {
+37 -1
View File
@@ -80,6 +80,7 @@ extern int web_compose_form(char *args_json, char **out_json, char **err_msg);
extern int web_app_new(char *args_json, char **out_json, char **err_msg);
extern int web_app_route(char *args_json, char **out_json, char **err_msg);
extern int web_db_update(char *args_json, char **out_json, char **err_msg);
extern int web_db_update_if(char *args_json, char **out_json, char **err_msg);
extern int web_db_delete(char *args_json, char **out_json, char **err_msg);
extern int web_db_query(char *args_json, char **out_json, char **err_msg);
extern int web_db_count(char *args_json, char **out_json, char **err_msg);
@@ -183,6 +184,7 @@ static int register_core(void) {
if (host_register((char *)"web_db_select", (char *)"url,table,where,limit,order,offset,txn", web_db_select) != 0) return 1;
if (host_register((char *)"web_db_get", (char *)"url,table,id,txn", web_db_get) != 0) return 1;
if (host_register((char *)"web_db_update", (char *)"url,table,id,row,txn", web_db_update) != 0) return 1;
if (host_register((char *)"web_db_update_if", (char *)"url,table,id,row,expect_col,expect_val,txn", web_db_update_if) != 0) return 1;
if (host_register((char *)"web_db_delete", (char *)"url,table,id,txn", web_db_delete) != 0) return 1;
if (host_register((char *)"web_db_exec", (char *)"url,sql,args,txn", web_db_exec) != 0) return 1;
if (host_register((char *)"web_db_query", (char *)"url,sql,args,txn", web_db_query) != 0) return 1;
@@ -264,7 +266,7 @@ static int register_core(void) {
if (host_register((char *)"web_cache_exists", (char *)"url,key", web_cache_exists) != 0) return 1;
if (host_register((char *)"web_cache_ttl", (char *)"url,key", web_cache_ttl) != 0) return 1;
if (host_register((char *)"web_app_proxy", (char *)"app,path,upstream,stream,strip_prefix,methods,headers_from_env,timeout_ms", web_app_proxy) != 0) return 1;
if (host_register((char *)"web_app_invoke", (char *)"app,path,method,fn,body,return", web_app_invoke) != 0) return 1;
if (host_register((char *)"web_app_invoke", (char *)"app,path,method,fn,body,return,class", web_app_invoke) != 0) return 1;
if (host_register((char *)"web_api_key_check", (char *)"key,authorization,pepper,keys", web_api_key_check) != 0) return 1;
if (host_register((char *)"web_render_nodes", (char *)"page,nodes,db,title", web_render_nodes) != 0) return 1;
if (host_register((char *)"web_render_document", (char *)"page,body,db,title", web_render_document) != 0) return 1;
@@ -994,6 +996,40 @@ func web_db_update(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
return replyJSON(outJSON, errMsg, out, err)
}
//export web_db_update_if
func web_db_update_if(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
url, err := dbURLOf(args)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
tableName, err := argStrReq(args, "table")
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
id, err := argStrReq(args, "id")
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
expectCol, err := argStrReq(args, "expect_col")
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
expectVal, ok := args["expect_val"]
if !ok {
return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing expect_val"))
}
row := args["row"]
if row == nil {
row = map[string]any{}
}
out, err := db.UpdateIf(url, tableName, id, row, expectCol, expectVal, txnOpt(args))
return replyJSON(outJSON, errMsg, out, err)
}
//export web_db_delete
func web_db_delete(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)