Skip to content

feat(runtime): route calls by id to a live Session or line - #2174

Merged
eric8810 merged 37 commits into
mainfrom
dim/2127-routing
Nov 26, 2026
Merged

eric8810 merged 37 commits into
mainfrom
dim/2127-routing

Conversation

@eric8810

@eric8810 eric8810 commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Base-1 of #2015, on the decided shape of #2127#7162130335 and ADR 027 as amended by #2200. Rebased onto ade859730. Draft.

Two operations, called directly

Whoever holds the instance selects the target, from the table it already has; there is no route object and no separate index.

Caller Operation
a Session's part, its own line sessionScope.lineCall({ lineId, service, method, args })
a Session's part, a Session face sessionScope.call({ service, method, args })
a process part sessions.call({ sessionId, lineId?, service, method, args })
  • sessionScope is new here (Session group), holding its Session and no other: lineCall takes no sessionId, and a line of another Session answers NoLine. base-3 adds describe().
  • sessions.call loads the Session through Agents' acquire and holds it while the call runs (D5); with lineId it then calls the same sessionScope operations in that instance, so both segments share one implementation.
  • A line is selected from TimelineTree's published: the published view both paths see, so a line that is open but not yet published answers NoLine. A closing line answers NoLine (the is_closing check is kept, because published still returns it).
  • Each call looks the target up again; a resolution is never kept (D4). Rust calls the same operations — it builds args from the target operation's request type and reads the reply as that operation's reply type. No typed entry exists: LineHandle::get, line(&scope, …) and session_face are gone, and no allowlist entry was added for them (ADR 027 D3).

Reach is judged once (route::face) for every call: a name the assembly marks internal(reason), a registration point (sessionMethods, toolRegistry, promptRegistry, guideEntries, submitChecks) or a scope lifecycle service answers NotDataFace; a data face of the other scope answers WrongScope.

Answers

Answer When
NoSession the Session is not there, has no owner, or is closed
SessionClosing the Session is closing, a line target too, and one that starts closing mid-call
SessionReloading Agents is reloading; retry later
SessionUnavailable { reason } the Session exists but cannot load: a failed restore, an unavailable Agent
NoLine the Session is live but the line is not published, closing, closed, or not its own
Routed { name, message, data, retryable } the target owner's own failure: its name, message, the structured value its error carries (Error::data()), and whether the owner says it may be retried

A Session part's TypeScript caller reads the same structure: RouteError serializes, so RouteErrorThrown's data carries owner { name, message, data, reloading }.

The owner's failure is retryable only when the owner's own code says so (Reloading), read with the bridge's Error::code(): a permanent failure is never retried, whatever its text says.

SessionsCall's Session arm declares lineId?: never, so a Session service passed with a lineId is refused by tsc instead of reaching WrongScope at runtime.

NoSession and SessionUnavailable follow Agents' own classification: a Session that no Agent owns and that has no stored rows is no_session; one with stored rows that cannot be loaded answers session_unavailable with the reason. A Session that closed itself keeps its rows, so it answers session_unavailable; a deleted one answers no_session.

The five selection answers carry their own codes on the sessions face (no_session, session_closing, session_reloading, session_unavailable, no_line); the owner's failure is routed and is retryable only when the owner's own error says reload.

Types

xtask -- types generates the request types for both operations: service is a data face of the target scope, method one of that face's methods, and args that method's parameters (LineCall, SessionCall, SessionsCall). A wrong service, a wrong method or wrong arguments fail tsc. The faces and their groups are read from the registration calls themselves — both register calls and catalog.register_shared_instance("name", GROUP) method calls — and the names an assembly marks internal are left out, from the single-name marks and from the product's (name, reason) table. A face whose type has no generated interface (timelineStore, timelineFactory, collaborationSession) is not offered: there is no type to give its methods. runtime/fixtures/branch-calls.ts plus nine @ts-expect-error cases is typechecked by runtime/plugin-sdk.test.mjs.

The authoring guide shows only these operations (Calling a Session or line by id).

Access layer

xtask/access-layer.json gains, per §5's exception, three groups and nothing else:

Source Entries Why
#2002 (HostPlatform) 33 skipped methods, Rust-only methods and fields, Session::service_opt
main after this branch started (fbd65fa82, b802a3f7d); #2226 (244d231b) moves them to BranchOpening 4 BranchLifecycle::opening_budget, admit_opening, admit_opening_with, finish_opening — not this PR's code; tracked by #2213 and #2226. Whichever of the two merges later deletes these four entries.

173 total, nothing removed this round. The two entries that came from main are #2213's to remove once that issue fixes BranchLifecycle's opening registration surface; this PR does not touch that implementation.

Verification

  • cargo clippy over the touched crates (dim-agent-runtime, dim-app-server, dim-agent-capabilities, dim-agent-scheduler, xtask-check), all targets: clean.
  • cargo run --locked -p xtask -- check: passes (access layer 171, declarations, plugin documents, i18n, comment links, literal main).
  • node --test runtime/plugin-sdk.test.mjs: passes — the generated requests reject unknown services, unknown methods and wrong arguments, and the fixture's valid calls compile.
  • dim-agent-capabilities routing_flow: 6 pass (own line and faces, SessionClosing while closing, NoLine after an end while the Session's other calls arrive, a language call over a bug session, reach refusals, idle unload and reload).
  • dim-app-server routed_call_flow: a minimal host with the offline model catalog launches a Session, answers a face call, reloads it after an idle release (D5), and observes a retryable session_reloading across an Agents restart followed by a successful retry.
  • dim-agent-scheduler data_faces_flow: sessions.call over a bridge reaches a Session's face and a line's, answers no_session for an unknown id and after a sessions.delete, no_line for a missing line, and session_unavailable for a Session that closed itself (its rows remain but Agents cannot load them).
  • cargo test -p dim-agent-integration-tests --locked: passes.

Typed replies, and the generated set against the runtime

  • ReplyOf<C> reads the target method's own return type from the generated interface. SessionScope.lineCall/call (declaration-merged, so the generic form is the one a caller sees) and the injected sessions.call answer ReplyOf<C>; the fixture asserts a valid reply type and that a wrong one is refused. Faces without a generated interface (timelineStore, timelineFactory, collaborationSession) are not offered at all, rather than offered untyped.
  • xtask -- check compares the two in both directions: every name the file offers must be one route::resolves accepts and the assembly provides, and every data face the route resolves that the file declares an interface for must be offered. Proved both ways — offering loopState fails with "offers names the route refuses", dropping branchLine fails with "does not offer routable data faces".

Review round: what changed

  • The owner's failure is no longer flattened into text: Owner { name, message, data, reloading } keeps the structured value the owner's error carries, and sessions.call forwards it as Routed { name, message, data, retryable }. A caller can act on the same structure a direct call would read.
  • The catalog check consumes the access layer's removed list again, so a retired service name cannot return unnoticed; proved by listing sessionIdentity.
  • The authoring guide states when a line stops being admitted: a running line that ended a tool call keeps that batch and stays selectable until its turn ends, so a call placed between the two still reaches its owner; the turn's durable branch/end is what answers no_line afterwards, and a call admitted before it keeps its owner's own result.

Operations a routed call cannot keep alive

An operation that needs a cancellation the caller observes through the future, or hands the caller something to settle, keeps its lifetime only when it is called directly. They are excluded on both sides from one hand-maintained list the runtime owns (route::LIFECYCLE_METHODS); the generator reads that same constant, so the runtime and the declarations cannot disagree:

Service Operation Why
dispatcher consume, listen take a function; consume hands the caller a subscription
permission check takes cancelled: () => void | Promise<void>
toolHost execute takes a cancelled callback
treeCommands create takes a cancelled callback
wait wait takes a cancelled callback

uiResources.publishFile/withdraw are there too: both take the calling row, which a routed call cannot carry. The runtime refuses them with RouteError::MethodNotRoutable (permanent), the generator reads the same list and emits Omit<Face, 'method'> in the authoring types, runtime/fixtures/branch-calls.ts asserts wait.wait is refused at compile time, and routing_flow asserts the runtime refusal for wait.wait and treeCommands.create. Runtime and declarations therefore cannot drift.

Review round (line comments + maintainer note)

  • sessionScope is no longer one of the Session faces a routed call resolves. It resolves a line and the Session's faces; sessionScope.call therefore cannot reach sessionScope.lineCall, the generated SessionFaces drops it, and routing_flow asserts the refusal. sessionScope.call stays for the caller that selected a Session by id, as the guide says.
  • sessions.call answers the same codes as the Session scope (not_data_face, method_not_routable, wrong_scope), and session_unavailable/no_line carry reason/line beside the message, so a caller reads them instead of parsing text.
  • A replaced or stopping Agents index answers session_reloading (retryable) rather than a final no_session; a Session that starts closing while a line is being selected answers SessionClosing.
  • The retired-name guard covers instance-only names (catalog.key_in's OutsideInstance), proved by a unit test with sessionConfig.
  • data_faces_flow's head comparison no longer assumes that no fact publishes between two reads: the routed head must lie between the two direct reads.
  • The guide states each route's code spelling (snake_case for the sessions envelope, camelCase RouteError variants for the Session scope), the direct-only operations, and who sessionScope.call serves.

Review round: what is not done

  • The typed-failure and lifecycle parity test for one routable operation is not written. With the exclusion above, the operations whose lifetime a routed call cannot keep are gone, so the parity claim holds for the rest by construction; a test that pins it for one operation (a failing timeline.query, say) is still missing.
  • The admission path now has a host: crates/dim-app-server/tests/routed_call_flow.rs serves a minimal AgentBuilder (capabilities and mock hosts only, no Scheduler) with ServerConfig { model_catalog: offline AimuxModels, database_path, unix_path, product_home: None }. It proves two of the four points on a Session Agents admitted through sessions.launch: a face call answers; Session::unload_if_idle takes the Session out of the Agent; and the next sessions.call restores it (D5). A third, the transient answer, is pinned at its mapping: a routed call while the Agents index is replaced answers session_reloading (retryable).
  • Still missing from that list: an end-to-end test of the replacement itself (reloading the Agents row from the test and calling inside the gap) and of the hold observed across dispatch (a blocking owner call while the idle pass runs). Both need a handle the test does not have today — a reload of a named row, and an owner operation that blocks — so the reload is pinned at the mapping and the hold at acquire's documented behaviour.

Still open

  • The access check's three boundaries: it matches a bare type name (not a path), exempts a whole type that derives Serialize, and exempts associated functions without self.
  • call_face reports a face with no dispatch as Owner { name: service } rather than a routing answer. The target has no name to keep a kind for, so the message says it is not provided.
  • A call admitted before a line's durable branch/end keeps its owner's result, and a running line stays selectable until its turn ends; neither window has a test that holds it open.
  • D5 is proven for a Session Agents admitted, and unmet for a Session created directly on an Agent. routed_call_flow launches through Agents, releases the Session with Session::unload_if_idle, and the next sessions.call restores it. A Session created straight on the Agent cannot be restored, because AgentIndex never records it: at the call Inner::versions has no entry, Inner::owner answers only through its live-Session fallback, and after the release that fallback answers None, so acquire_checked takes its store.has_records arm and answers Storage("Session … has no available owner") — reported as session_unavailable. Recorded in 按 id 调用:由持有实例的一方选目标(base-1) #2127 for 所有者扫描:Agent 目录与协作 #2020.
  • The same limit applies to the business close: RunningServer::close_session answers ok for such a Session and the next call restores it, because Agents' index does not know it. The tests therefore assert what they can observe: a Session that closed itself keeps stored rows Agents cannot load (session_unavailable), and a deleted one is no_session.
  • The hold an admitted call takes across dispatch is not observed in a test: it is slot.uses > 0, which Agents' idle pass skips, and observing it needs an owner operation that blocks (the blocking face operations are the ones this PR excludes).

Refs #2015
Refs #2127

@eric8810

Copy link
Copy Markdown
Collaborator Author

计划在本 PR 开出后改了两处,都属于 base-1,请在本 PR 里补上。详见 #2015 计划更新。

  1. Session 部件只按 branchId 路由到本 Session 的线。
    • PR 描述里写的是「Session 部件读进程的 route,自己传 session id」。这样 Session 部件就能访问别的 Session 的线。
    • 请提供绑定本 Session 的入口:Rust 用 line_owner::<T>(lineId),其他语言用 route.line({lineId, service, method, args})。这两个入口都不接受 sessionId。
    • base-2 迁移 Session 上的转发方法时要用到它。
  2. xtask/check/src/access.rs 增加一类违规: 对外服务的类型在 #[rutis::service] 块之外还有带 self 的 pub / pub(crate) 方法,或者有 pub / pub(crate) 字段。
    • 不算违规的:只在本插件装配时使用、不带 self 的构造函数。
    • 现有的违规一并列进 access-layer.json。

@eric8810

Copy link
Copy Markdown
Collaborator Author

补充一处:插件作者怎么写按 id 的调用。这一处属于 base-1,请在本 PR 里补上。

作者不直接写 route。 现在 TS 调用方要写 route.line({ lineId, service: "inputQueue", method: "withdraw", args }):服务名和方法名都是字符串,参数和返回值没有类型,同一个操作也多出了一种写法。

改为在 route 上面生成带类型的写法,作者调用的就是目标服务自己的方法:

  • 进程部件:session(sessionId).line(lineId).inputQueue.withdraw(id);调 Session 的服务时写成 session(sessionId).sessionScope.describe()
  • Session 部件:line(lineId).inputQueue.withdraw(id),只能到本 Session 的线(上一条评论的第 1 处)
  • Rust 用同样的形状

要求:

  1. session(...) 和 line(...) 只记地址,不做查找。 每次调用方法时才按 id 查找,查找失败时,这次调用就返回 NoSession、SessionClosing 或 NoLine。调用方拿不到可以保存的对象(ADR 027 D4)。
  2. session(...) 是运行时提供的写地址入口,不是现在的 Rust Session 对象。 Session 上不加任何查找方法(ADR 027 附录 F;base-2 也要删掉它上面按线名转发的方法)。
  3. route 只用作运行时内部转送调用的通道。 它不写进 SDK 文档和插件作者指南。npm/branch-services.d.ts 里提供上面这种带类型的写法。

@zerob13 zerob13 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What this does

Adds a process-level route face: sessionId or (sessionId, lineId) plus a service/method is resolved to the live owner and forwarded, with NoSession / SessionClosing / NoLine. Also adds the xtask-check access-layer scan with a 115-entry baseline.

Blocking

  1. Owner errors are not passed through unchanged. crates/dim-agent-runtime/src/route.rs:245 maps every HostDispatch::invoke / settle failure to AgentError::Fault. A language caller of route.line(...) therefore receives Fault, not the owner's BranchEnded, BranchRefused or InvalidInput; only the Rust line_owner path preserves the error type. The module docs, the PR body and docs/design/contracts/runtime-owner-operations.md all say "unchanged". Either preserve the owner's error kind on the by-name path or narrow the contract to "the message is preserved", and add a test where an owner method fails through route.line.

  2. The allowlist does not enforce its "only shrink" rule. xtask/check/src/access.rs:94 compares the found set with allow in both directions, but never against a base revision, so adding a new violation together with its matching entry still passes. removed in xtask/src/catalog.rs:59 has the same property. Either compare the allow set with the merge base in CI, or remove the guarantee from the code comment and PR body and treat it as a review convention.

Should fix

  • The by-name path has no scope gate. route.rs:183 / route.rs:196 only refuse five literal registry names and the two lifecycle services. The typed path also checks the catalog group (session_face / public), but the by-name path reaches anything that has a dispatch at the instance key. Concretely timelineStore (assembly.rs:1244) and sessionLoader (session_typescript.rs:53) become reachable cross-Session: a language part can append to another Session's store or create/remove its instances by id. Decide whether those are routable; if not, refuse them, and derive the names with names::name_of so a rename cannot silently widen the gate.
  • The line index is registered before publication and never pruned. assembly.rs:1564 registers at TimelineContext::start, before TimelineTree publishes the line; lines (assembly.rs:1183-1191) never removes ended lines. §10 says a line still opening is not a line yet. Resolve through the tree's published lookup, or gate on publication and prune on close.
  • A close racing a call can answer outside the table. resolve_session checks closing once, then loaded() (assembly.rs:1164) can return Closed if the subtree was released in between; a line target can answer NoLine instead of SessionClosing in the same race. Map those to the three answers or re-check after loading.

Nits

  • SessionForwarding matches only a parameter literally named branch (access.rs:217). It misses line_id / branch_id forwarders and flags tree operations such as Session::end_branch. The baseline reproduces today, but the check does not test the stated rule.
  • The refusal test covers sessionMethods and toolRegistry, not promptRegistry, guideEntries or submitChecks; there is also no owner-error test through the by-name path.
  • "Only adds; deletes nothing" is not exact: testing.rs always installs process rows now (has_plugins removed) and the timelineTree.call paragraph is replaced. The -1720 is generated-id churn.

Checked: full 31-file diff against main, ADR 027 D1-D4, principles §7, runtime-owner-operations.md, routing_flow.rs, access.rs and the 115-entry baseline (50 service-skip / 41 host-dispatch / 23 session-forwarding / 1 branch-type). CI green per the PR; workspace tests were not rerun locally.

@eric8810

Copy link
Copy Markdown
Collaborator Author

按 id 调用的写法(定稿):本条取代上一条评论,并回答「session(...)/line(...) 背后由谁提供」。

结论:不再单独做 route 对象。持有者自己负责查找:Session 由 Agents(sessions)找,线由所属的 Session(sessionScope)找。都在 Dim 里实现,不改 rutis。

作者写法(Rust 和 TS 一样)

调用方 写法
同一条线上的部件 照旧注入,直接调:inputQueue.withdraw(id)
Session 部件 sessionScope.line(lineId).inputQueue.withdraw(id)
进程部件 sessions.session(sessionId).line(lineId).inputQueue.withdraw(id)
进程部件调 Session 的服务 sessions.session(sessionId).sessionScope.describe()

Rust 在最后一步写明类型,例如 .line(lineId).get::<InputQueue>()?.withdraw(id)。拿到的服务只在这一次调用里使用,不保存。

规则

  1. session(...) 和 line(...) 只是地址,不做查找。每次调用方法时才查找,失败时这次调用返回 NoSession、SessionClosing 或 NoLine。
  2. sessionScope.line(...) 只能找到本 Session 的线,所以 Session 部件不传、也不能传 sessionId。
  3. Rust 的 Session 对象上不加查找方法(ADR 027 附录 F)。

底层:两个数据面操作,两种语言共用

  • sessionScope.lineCall({ lineId, service, method, args })
  • sessions.call({ sessionId, lineId?, service, method, args })

链式写法由 Dim 在这两个操作上生成:

  • TS 生成在 dimcode 包里,类型来自 branch-services.d.ts,服务名、方法名、参数和返回值都有类型;
  • Rust 生成在 dim-agent-runtime 里。

作者文档和示例只写链式写法。

对本 PR 的改动

  • 删掉 Route 对象和 route 服务(route.session、route.line)。
  • 线的索引保留在每个 Session 里,由 sessionScope 提供;Session 的索引由 Agents 提供。
  • 三种错误、拒绝登记点和生命周期服务、访问层检查和允许名单都不变。

sessionScope 这个服务目前还没有,describe() 要到 base-3 才加。本 PR 先建立这个服务,只提供 line / lineCall;base-3 再往里加 describe()。

eric8810 added a commit that referenced this pull request Nov 25, 2026
A plugin calls a Session's or a line's data face with the operation the index
owner serves: `sessionScope.lineCall` for its own Session's line,
`sessions.call` for a Session or a line of it. No chain and no wrapper: rutis
serves a Rust service's reply as data, so an object a caller continued to call
was never available (maintainer correction on #2174).

`xtask -- types` narrows both requests to what a route resolves: `service` is a
data face of the target scope, `method` one of its methods, and `args` that
method's parameters, so a typo fails `tsc`. The injected `sessions` type
carries `call`, and the authoring guide shows the two operations.

Refs #2015
Refs #2127

@yyhhyyyyyy yyhhyyyyyy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The shape

I agree with what base-1 does: each owner keeps its own index and does the lookup, the two operations pass the owner's own arguments, reply and error through, and no address object or chain is handed to an author. Everything below is about the line index behind sessionScope, because the branch tree work and the Goal work after this will be built on it.

I read head f5d21296c353 against ADR 027 D1 to D4, §7 and the timeline rules.

1. A line is routable before it publishes (blocking)

I agree with the point in the earlier review at 672fb9bfe (review) that the line index must be gated on publication; what a call reaches in that window is what it did not spell out.

The index is written where the line is built, not where the tree publishes it: SessionAssembly::lines (assembly.rs) is filled by register_line (assembly.rs) from the timeline factory right after TimelineContext::start (assembly.rs), and the tree calls that factory from launch (timeline_tree.rs).

Publication happens later in the same task: the opening branch/start and its input are appended and finish_opening waits for that batch (timeline_tree.rs), and only then does the line activate() and get its ready value (timeline_tree.rs). Until that point the tree hides the line: get and published answer nothing for it (timeline_tree.rs) and the directory skips it (timeline_tree.rs), which follows the rule that a line still opening is not a line yet (timeline-branches.md).

A routed call does not check that. The module docs list closing, closed and another Session's line as NoLine (route.rs) and have no case for a line that has not published. SessionScope::line_context asks SessionAssembly::line, which upgrades the weak reference and tests only is_closing (assembly.rs). So between the registration at assembly.rs#L1566 and the publication at timeline_tree.rs#L1355, a sessionScope.lineCall or sessions.call reaches a line whose parts are mounted but not activated, since activation is what starts their work (timeline_context.rs), whose opening input is not published, and which is rolled back if finish_opening fails or the create is cancelled. A call that fails there also loses its kind: the route answers the owner's failure as the single owner code with only a name and message (route.rs, route.rs), so a caller cannot tell a transient failure caused by the window from a permanent one. The id is not a secret in that window: the parent's committed branch/create carries it (timeline_tree.rs), so a caller that reads the parent's history can name the line before it exists as a line.

What I would ask for: record the line where the tree publishes it, next to ready.send_replace or by asking the tree's published lookup, and answer NoLine for a line that has not published. A test that routes while a create is held open would pin it; routing_flow covers a closing Session and a closed line, not an opening one.

2. An ended line and an unknown id answer one code (blocking)

RouteError::NoLine covers a line that is closing, closed, or was never one of this Session's (route.rs), and SessionAssembly::line cannot tell them apart: an ended line's context is gone, so the upgrade fails and the entry is dropped (assembly.rs). The tree does tell them apart under one lock: published answers BranchEnded for a line it ended and UnknownBranch for an id it never had (timeline_tree.rs), and that difference is what lets a caller fall back to the ended read instead of giving up.

That difference matters more after the branch tree PR: the point of moving ended reads into the tree is that a caller asks for a line without first knowing whether it is open, and a routed read of a finished line should answer its fixed head rather than a permanent error. With one no_line code a caller cannot tell "this line finished, read it through the tree" from "this id is wrong, stop retrying". If a routed call has to stay final for an ended line, I would still keep the kind, as BranchEnded and UnknownBranch or as two codes, so each caller does not have to reclassify it itself.

3. An ended line keeps its index entry (should fix)

I agree with the other half of the earlier review at 672fb9bfe (review), that the index must be pruned when a line closes; the size below is what it did not spell out.

lines has one writer (assembly.rs) and one reader (assembly.rs), and an entry is removed only when a later call happens to name the same dead id (assembly.rs). Ending a line removes its node and records it as ended (timeline_tree.rs), but nothing tells the Session to drop the routing entry, and a failed build leaves one too because that path only removes the node (timeline_tree.rs). A Session that opens tool lines or Goal evaluation lines therefore keeps one entry per line it ever created, for the rest of its life.

I would remove the entry where the line stops being routable: when the tree ends the line, and when a build fails.

4. Minor: names fixed at compile time are rebuilt per call

face builds name_of::<SessionLifecycle>() and name_of::<BranchLifecycle>() on every call (route.rs), and name_of allocates a character vector and a string each time (names.rs). call_face builds the dispatch key from the name again (route.rs), which is one owned string inside the key, and LineHandle::get adds the same for T (route.rs). That is three name builds per routed call for values that are known when the crate compiles. The two lifecycle names can sit as constants beside REGISTRATION_POINTS, and the typed entry can pass a static name to the same gate; no interface changes.

@eric8810

Copy link
Copy Markdown
Collaborator Author

Rust 的按类型取辅助:去掉。

  • 删掉 line(&scope, lineId),不为它加允许名单条目。
  • Rust 和 TS 一样,只用 sessionScope.lineCall 和 sessions.call 这两个操作。Rust 调用方用目标操作的请求类型构造 args,再把返回值解析成它的回复类型。

理由:

  • 按类型取会绕过数据面,直接拿到 Rust 对象,等于第二个入口。写成自由函数,只是让访问层检查认不出来。
  • 允许名单只减不增。

已更新 #2127 的已定决定。

@eric8810

Copy link
Copy Markdown
Collaborator Author

回答"sessions.call 和 ADR 027 D1 冲突"的问题:改 ADR,本 PR 的写法保留。

ADR 027 改为由持有实例的一方按 id 选目标,见 #2200。

  • 本 PR 的 sessions.call 和 sessionScope.lineCall 正是这个形状,不用再找别的地方放。
  • D1 禁止的是"每个操作各开一个转发方法",按 id 选目标的调用不算。

本 PR 还要改的:

  1. 删掉 Rust 的 line(&scope, lineId),不加允许名单条目(见上一条)。
  2. sessions.call 在调用期间取保持:Session 没加载就先加载,用 Agents 现有的 acquire,和 sessions 现有方法、Rpc 一样。现在遇到没加载的 Session 会直接返回 NoSession,这样 Scheduler、Collaboration 迁移过来以后,就够不到没加载的 Session。
  3. TS 一侧只声明这两个操作的类型,不生成链式写法,也没有运行时包装。

sessionMethods 不动,它只服务客户端协议。

完整决定见 #2127 的已定决定。

@eric8810

Copy link
Copy Markdown
Collaborator Author

补充:session_face::<T>(&scope) 和 LineHandle::get::<T>() 都是按类型取对象的入口,按 ADR 027 D3(#2200)一起删掉,不加允许名单条目。PR 描述里列出的这两种 Rust 写法也要删掉。Rust 调用方改用 sessionScope.lineCall 和 sessions.call:用目标操作的请求类型构造 args,再把回复解析成它的回复类型。

@eric8810

Copy link
Copy Markdown
Collaborator Author

按 #2200 里 zerob13 的评审,本 PR 还要改两处(已写进 #2127 正文和已定决定):

  1. 去掉 SessionAssembly 里新加的 lines 表。 线在 TimelineContext 建好时就登记进这张表(assembly.rs:1566),比线发布还早,所以还没发布的线也能被调到。改为查 TimelineTree 的 published:它只认已发布、未结束的线,返回的 Branch 里带着 TimelineContext。这样进程调用方和 Session 部件看到的是同一份发布状态,也不会多出一张表。

  2. sessions.call 加载失败时,多答两种错误。 acquire 失败时按下面映射:

    • Reloading(进程还没准备好)→ SessionReloading,调用方稍后重试;
    • Storage,或者恢复出错 → SessionUnavailable { reason },调用方把原因报告出去;
    • Closed → NoSession。

    这些错误都在调用目标的操作之前返回。

Collaboration 的请求和客户端 attach 现有的保持都不变。

@eric8810

Copy link
Copy Markdown
Collaborator Author

再补一处(yyhhyyyyyy 在 #2200 指出):sessions.call 现在把所有错误都压成了 Rejected { message }(sessions.rs:925-930)。Routed 定义了,但没有任何地方构造它,而且 Rejected 不可重试,所以目标所有者返回的重载错误到了调用方就变成了永久失败。

改法(已写进 #2127 的已定决定):

  • 选不中和加载不了的五种错误(NoSession、SessionClosing、SessionReloading、SessionUnavailable、NoLine)各用自己的错误码;
  • 目标所有者的错误用 Routed 返回,保留它的名字和内容;
  • 是否可重试跟着错误走:SessionReloading 和目标所有者返回的重载错误可以重试。

scheduler 测试里断言 error.code == "rejected" 的地方(data_faces_flow.rs:828-870),要跟着改。

@eric8810

Copy link
Copy Markdown
Collaborator Author

本 PR 先暂停,等 ADR 027 的修改 #2200 合并后再继续。

合并后,按 #2127 的已定决定一次改完以下五处(详见前面几条评论):

  1. 删掉 LineHandle::get 和 session_face;
  2. sessions.call 在调用期间加载并保持 Session;
  3. 去掉 SessionAssembly 的 lines 表,改查 TimelineTree 的 published;
  4. 加载失败时回答 SessionReloading 或 SessionUnavailable;
  5. 错误不再压成 Rejected,目标所有者的错误用 Routed 原样返回。

eric8810 added a commit that referenced this pull request Nov 25, 2026
A plugin calls a Session's or a line's data face with the operation the index
owner serves: `sessionScope.lineCall` for its own Session's line,
`sessions.call` for a Session or a line of it. No chain and no wrapper: rutis
serves a Rust service's reply as data, so an object a caller continued to call
was never available (maintainer correction on #2174).

`xtask -- types` narrows both requests to what a route resolves: `service` is a
data face of the target scope, `method` one of its methods, and `args` that
method's parameters, so a typo fails `tsc`. The injected `sessions` type
carries `call`, and the authoring guide shows the two operations.

Refs #2015
Refs #2127
A minimal host serves with the offline model catalog and no product home, so
`sessions.launch` works and the Session is admitted by Agents:
`crates/dim-app-server/tests/routed_call_flow.rs` launches one, answers a face
call, releases it with `Session::unload_if_idle` (it leaves the Agent), and then
`sessions.call` restores it — D5's "load and hold for the call" measured on the
production path rather than on a Session created behind Agents' back.

While the Agents index is being replaced a routed call answers
`session_reloading` (the one transient answer, so a caller retries), pinned by a
test of the mapping.

Refs #2015
Refs #2127
… serialize the route error

- `LIFECYCLE_METHODS` gains `dispatcher.listen` and `dispatcher.consume`: both
  take a function, and a routed call carries data only. The list is hand
  maintained, and the generator reads this same constant, so runtime and
  declarations agree; the fixture and `routing_flow` assert the refusal.
- `RouteError` serializes, so a Session part's TypeScript caller reads the
  owner's structured failure (`owner { name, message, data, reloading }`)
  exactly as the process segment and Rust callers do.
- the authoring guide and the issue record say what the code does: the durable
  `branch/end` takes a line out of the published set at once, so a later call
  answers `no_line`; a call admitted before it keeps its owner's result.

Refs #2015
Refs #2127
… operations excluded

- `sessionScope` is no longer one of the Session faces a routed call resolves:
  the scope resolves lines and the Session's faces, it is not one of them, so
  `sessionScope.call` cannot reach `sessionScope.lineCall`. The generated
  `SessionFaces` drops it, and the test asserts the refusal.
- `uiResources.publishFile`/`withdraw` join the excluded operations: they take
  the calling row, which a routed call cannot carry.
- `sessions.call` answers the same codes as the Session scope (`not_data_face`,
  `method_not_routable`, `wrong_scope`), and its `session_unavailable`/`no_line`
  carry `reason`/`line` instead of folding them into the message.
- a replaced or stopping Agents index answers `session_reloading`, retryable,
  instead of a final `no_session`; a Session that starts closing while a line
  is selected answers `SessionClosing`.
- the retired-name guard covers instance-only names (proved with
  `sessionConfig`), and the head comparison in `data_faces_flow` no longer
  assumes no fact publishes between two reads.
- the guide states each route's code spelling, the direct-only operations, and
  who `sessionScope.call` serves.

Refs #2015
Refs #2127
…ures

`LIFECYCLE_METHODS` is no longer a hand-written list nobody checks: `xtask`
reads every `#[rutis::service]` block, finds the operations whose parameters are
the calling row, a cancellation or a callback, keeps those the declarations
export in a routable scope, and fails when the two disagree in either direction —
an operation that cannot cross but is not listed, or a listed one whose signature
can.

Proved both ways: dropping `uiResources.withdraw` from the list fails with
"not listed: [uiResources.withdraw]", and adding `sessionConfig.get` fails with
"listed but routable: [sessionConfig.get]".

Refs #2015
Refs #2127
`BranchLifecycle::opening_budget` (a service-skip) and
`BranchLifecycle::admit_opening_with` (a Rust-only method) come from main
(#1997/#2198 era, `fbd65fa82` and `b802a3f7d`), not from this branch; they are
in the allowlist now so the check can run against the merged tree.

Entries: 171 -> 173, both from main.

Refs #2015
Refs #2127
`RunningServer::restart("Agents")` reloads the row the routed call needs, so a
test can hold the window open: the minimal host launches a Session, restarts
Agents while calls are in flight, and asserts at least one
`session_reloading` that says `retryable`, then a retry that answers. Measured
7-8 transient answers out of 150 calls per run.

Refs #2015
Refs #2127
…id-call

Also drop the stale method count from the authoring guide, and state in the
contract page that the two surfaces spell the same failure differently.

Refs #2015
Refs #2127
…ivation

- `routed_call_flow` is `#![cfg(unix)]` (a Unix socket host) and says so; Windows
  never builds it.
- `npm/plugin.d.ts`'s `SessionsError` is the generated union again, so a caller
  reads `reason`, `line`, `service`, `name` and `data` instead of casting.
- the guide, and the PR, state the real admission cutoff: a running line that
  ended a tool call stays selectable until its turn ends; the turn's durable
  `branch/end` is what answers `no_line` afterwards.
- the signature derivation has unit tests, and its documented limits name the
  shapes it does not recognize (`impl Fn`, a bare `fn` pointer, other aliases).

Refs #2015
Refs #2127
- `SessionsError` is the generated union intersected with the envelope's
  `retryable`, which `envelope()` adds to every failure; the fixture reads it on
  a non-`routed` code.
- the signature derivation also recognizes `impl Fn` and a bare `fn` pointer, and
  its doc says the shapes it still misses are a review-time guarantee.
- the line-scope doc links `SessionScope` instead of the removed `Route`, and a
  stale comment about routing codes is gone.

Refs #2015
Refs #2127
… NoSession

- the owner-operations table no longer mentions a compact-and-wait variant: a
  compaction that waits calls `agentLoop.compact` through `lineCall` and waits
  through the Session's `timelineTree`, because `lineCall` resolves only
  operations an owner already serves;
- the route's module docs name `SessionScope::call`, say the scope is not one
  of its own faces, and say that Agents loads a Session for the call, so
  `NoSession` means it does not exist or cannot load again (D5).

Refs #2015
Refs #2127
…n addresses

- the ten `@ts-expect-error` cases are inside `readByCalls`, where `scope` and
  `sessions` resolve, so each one now proves the call shape rather than a
  missing name;
- `LineCall` takes no `sessionId` and `SessionCall` takes neither `lineId` nor
  `sessionId`, with a case for each;
- the guide states the real cutoff: a line keeps answering after its durable
  end while `close_and_record` waits for `deliver_final`; entering closing is
  what answers `no_line`.

Refs #2015
Refs #2127
…'s code

- `SessionScope` is no longer a `PublicService`, so no `Session` read hands it
  out; `Session::routed_scope` is the owning instance's entry and Agents is its
  only caller (`dim-app-server`). A route is no longer reachable as a facade
  read.
- `RouteError::Owner` and `SessionsError::Routed` carry the owner's own `code`,
  read from the bridge error beside `reloading`: a routed failure now says
  `UnknownBranch`, not just a name and a message.

Refs #2015
Refs #2127
… code survives

A `compile_fail` doctest on `Session::routed_scope` shows
`session.session_service::<SessionScope>()` does not compile now that the scope
is no `PublicService`; a unit test shows a remote failure's own code
(`UnknownBranch`) reaches `RouteError::Owner` beside `reloading`.

Refs #2015
Refs #2127
… only shared faces

- `routing_flow` compares `InputQueue::withdraw`'s `InvalidInput` directly and
  through `lineCall`, so the owner's own code is proven to arrive unchanged.
- `face` requires `catalog.is_shared`: a native-only registration answers
  `NotDataFace`, which a Session part cannot reach. The rig shares the faces its
  cases use, the way the product's `share_names` does.

Refs #2015
Refs #2127
`Session::routed_scope` was a public method, so any crate with a `Session` could
still take the router and write the Timeline through `lineCall`. The entry is now
`dim_agent_runtime::route::routed_scope(&Session)`, which reads the owning
instance through a crate-private `Session::assembly`; the facade keeps no router
read, and two `compile_fail` doctests pin both ways it must stay unreadable.

The owner-operations table said the compact handler routed `agentLoop.compact`
and waited through `timelineTree`; those faces are internal and answer
`NotDataFace`, so the row now states the direct calls the code makes.

Refs #2015
Refs #2127
`call_face` now answers `Option<serde_json::Value>`: a method that replies
nothing settles as `BridgeValue::Undefined` and crosses as `None`, while the
owner's `null` stays `Some(Null)`. `SessionScope::call`/`line_call` and
`sessions.call` follow: the process envelope omits `value` for a void reply
instead of writing `null`, and the routed arm owns its envelope so it is not
wrapped twice.

Tests: `route::tests::a_void_reply_is_undefined_and_a_null_reply_is_a_value` for
the mapping, and `routing_flow::a_void_reply_stays_undefined_and_a_value_stays_a_value`
for a void `sessionLoader.remove` and a real reply through the route.

Refs #2015
Refs #2127
A bare `Session` had a public path to the router (`pub mod route`,
`pub use route::*`, `pub fn routed_scope`), so any crate holding one could write
the Timeline through `lineCall`. The module is private again and exports only
its data types; the router travels in `RoutedSession`, whose constructor is
crate-private, and the mechanism caller that owns the index takes one from
`Agent::routed_session(id)`. Three `compile_fail` doctests pin the ways a bare
`Session` has none: `session.routed()`, `routed_scope(session)` and
`RoutedSession::new(..)`.

Refs #2015
Refs #2127
- `RoutedReply<C>` makes the declaration honest about the two surfaces: a
  method that replies nothing reaches a routed caller as `null` (the bridge maps
  `Value::Undefined` to JSON null) while a direct call returns `undefined`; the
  fixture pins the `null`, and the contract and the guide state the difference.
- a Session that starts closing between the scope check and the router lookup
  answers `SessionClosing`, not `SessionUnavailable`.
- the paragraph that describes `Session::instance` sits on `instance()` again;
  `routed` has its own.

Refs #2015
Refs #2127
…n are

- `sessionScope` answers `null` for a method that replies nothing, while the
  `sessions` envelope leaves `value` out and a process caller reads
  `undefined`; the contract, the guide and the sessions-service page say so.
- `Session::instance` has its paragraph back; `SessionClosing` says the process
  envelope answers `session_closing` instead of claiming it reads as
  `NoSession`.
- the rig shares the mechanism names the product shares too, so the refusal of
  `sessionMethods`, `toolRegistry`, `guideEntries`, `sessionLifecycle` and
  `branchLifecycle` is asserted for being a registration point or a lifecycle
  service, not for being unshared.

Refs #2015
Refs #2127

@Simon-He95 Simon-He95 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the b7e5ef44..c27898de delta. It is docs, a restored Session::instance doc, and tests: the new routing cases pin that registration/lifecycle services are refused as non-data faces, and the contract now states the two reply shapes correctly (sessionScope sees null, the sessions envelope omits value and reads as undefined). No behavior regression; my approval carries.

The PR is now CONFLICTING after #2202 merged (the agent.rs / access-layer overlap). Rebase and rerun before merge; the Session::service_opt access-layer entry still has to be removed by whichever of #2174/#2206 lands second.

Main now takes `CreateSessionOptions` and `RestoreSessionOptions`; the two probe
rigs and the routing test pass the defaults. No interface change on this side.

Refs #2015
Refs #2127
@eric8810

Copy link
Copy Markdown
Collaborator Author

按 head 01f9a7064 核对,还要改一处,另有两件事:

1. 这个作用域里没装目标服务时,不能答成所有者的错误

  • route.rs:388:服务名合法,但这条线或这个 Session 上没有装这个服务(例如所用的 profile 不含 BackgroundExec)时,call_face 返回 Owner { name: 服务名, message: "... is not provided now" },到了 sessions.call 就成了 routed。
  • 这时没有所有者,这个错误也不是所有者写的。按 ADR 027 D2,选不中由持有者在调用目标操作之前回答;routed 只用来原样传递目标所有者自己的错误。
  • 请新增持有者的回答 NoService { service },sessions.call 上的错误码是 no_service,不可重试。生成的类型和作者指南一起更新,并加一个测试:调用一条没装这个服务的线。已写进 #2127 正文和已定决定。

2. 变基到最新的 main

base-4 已经由 #2202 合并,它改了所有创建和恢复 Session 的调用,本 PR 和 main 又有冲突了。

3. PR 描述按现在的实现更新

  • 表格里写着 Session 部件用 sessionScope.call 调 Session 的服务。已定决定是 Session 部件照旧注入,call 只给按 id 选中 Session 的一方用,作者指南已经这样写了。
  • 描述说 LIFECYCLE_METHODS 是手写名单,实际上 xtask 已经按方法签名核对它。
  • 允许名单的条数,一处写 171,一处写 173。

「Still open」里访问层检查的三处放宽,以及来自 main 的 4 条 BranchLifecycle 条目,都已记进 #2015 计划第五节,本 PR 不用改。

改完后请 yyhhyyyyyy 和 zerob13 重新评审。

@yyhhyyyyyy yyhhyyyyyy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: #2174 route calls by id to a live Session or line

Reviewed head 673342a0 against origin/main a8d84e93 (round 12), the full main...head diff. The branch was rebased onto the current main during this round; the old c27898de head is no longer in the history, so this review covers only the new history.

The r11 blocking P2 is fixed: the contract, the authoring guide and the sessions-service page now say per surface what a routed void answers. The rebase is lossless: git range-diff shows every branch commit identical except one import union in crates/dim-app-server/src/agents.rs, and the adaptation commit only passes CreateSessionOptions and RestoreSessionOptions defaults at two test call sites, which preserves the earlier one-argument behavior. No blocking finding.

Fixed at 673342a0

  • The per-surface routed void: docs/design/contracts/runtime-owner-operations.md:43-45, docs/typescript-plugin-authoring.md:70-72 and docs/design/appserver/sessions-service.md:144-145 say sessionScope answers null while sessions.call omits value and a process caller reads undefined. The call arm leaves value out (crates/dim-app-server/src/agents/sessions.rs:1021-1035), reply_value keeps an absent value apart from JSON null (crates/dim-agent-runtime/src/route.rs:459-463, :575-578), and SessionsError serializes the snake_case code (crates/dim-app-server/src/agents/sessions.rs:295). Withdrawing the r11 P2.
  • Session::instance has its paragraph again (crates/dim-agent-runtime/src/agent.rs:767-771), the same text main carries. Withdrawing the r11 P3.
  • The routing rig shares the six mechanism names and asserts NotDataFace for the registration points and lifecycle services (crates/dim-agent-capabilities/tests/routing_flow.rs:68-79, :497-523). All eight routing_flow cases pass. Withdrawing the r11 P3.
  • RouteError::SessionClosing now says a process caller reads session_closing and ends its work (crates/dim-agent-runtime/src/route.rs:66-68); routed() maps it at crates/dim-app-server/src/agents/sessions.rs:932. Withdrawing the r11 P3.

Cross-PR

  • #2226 (open, head 244d231b) moves the four BranchLifecycle opening methods. The PR description now lists all four (opening_budget, admit_opening, admit_opening_with, finish_opening) and says whichever merges later deletes the entries at xtask/access-layer.json:561, :566, :571, :576.
  • #2206 (open, head 68ff0118) removes Session::service_opt; the entry at xtask/access-layer.json:526 must go when it lands.
  • The rebased head passes the access check against main a8d84e93 (173 allowed), so neither main nor #2202 staled the list.

Optional (P3)

  • RoutedReply's comment still says "a routed call" without the sessionScope scope (npm/branch-services.d.ts:1944), and the fixture comment at runtime/fixtures/branch-calls.ts:41 repeats it. The guide now distinguishes the two surfaces, so scope these two comments the same way.
  • The PR description's verification line says the access layer check passes with 171 allowed; at 673342a0 cargo run --locked -p xtask -- check reports 173. Update the count.
  • SessionsService::invoke still passes through any reply with a top-level ok (crates/dim-app-server/src/agents/sessions.rs:909). Sound today because only the call arm produces one (:1021-1035), but a future method with an ok field would skip the envelope.
  • xtask/src/catalog.rs:137 links dim_agent_runtime::route::resolves, and route is private (crates/dim-agent-runtime/src/lib.rs:15). Point at dim_agent_runtime::resolves or drop the link.
  • No compile_fail pins session.session_service::<SessionScope>(); the existing case in crates/dim-agent-runtime/src/scope.rs:27 covers another type. The type is safe today, a case keeps it so.
  • Test gaps unchanged: no case holds an opening branch/start batch and asserts NoLine; an_owner_failure_keeps_its_code_through_the_route (crates/dim-agent-capabilities/tests/routing_flow.rs:378) puts the direct result only in the assertion message; the process envelope's routed shape is not asserted; and no test calls a void method through sessions.call, which is the surface the new docs sentence covers.
  • The owner contracts still omit the new method and face: docs/design/contracts/session-access.md:7 and docs/design/appserver/sessions-service.md:30-31 list the sessions methods without call, and docs/design/service-faces.md has no sessionScope row.

Verification

Run with LC_ALL=en_US.UTF-8, isolated HOME, TMPDIR, XDG and CARGO_TARGET_DIR under the review data directory, and the pinned 1.100.0 toolchain. Worktree clean at the head.

  • git range-diff 076df0a1..c27898de a8d84e93..673342a0: every branch commit identical except commit 5, whose only difference is the import union in crates/dim-app-server/src/agents.rs (CreateSessionOptions and RestoreSessionOptions beside RouteError). The old docs commit is 1c3a8524c with the same patch, and 673342a0 adds only the two test adaptations.
  • cargo run --locked -p xtask-check: passes, access layer 173 allowed.
  • cargo run --locked -p xtask -- check: passes, 43 plugin documents.
  • cargo fmt --all -- --check: passes.
  • cargo test -p dim-agent-capabilities --test capabilities_flow routing_flow::: 8 pass.
  • cargo test -p dim-app-server --lib a_routed_call_during_an_index_replacement_is_transient: pass.
  • cargo test -p dim-app-server --test routed_call_flow: 2 pass.
  • cargo test -p dim-agent-scheduler --features testing --test scheduler_flow a_process_call_by_id_reaches_a_live_session: pass.
  • node --test runtime/plugin-sdk.test.mjs: 2 pass.

Unverified: the runtime null for a routed void was not re-probed through a language connection at this head; it follows from reply_value and the fixture, as before. The sessions.call void omission is read from the code and still has no test, which is a test gap above. CI run 45807453955 at 673342a0: changes, scripts, static-checks, dependencies, macos-native, web and windows-cli pass; verify (linux) was still running when this review was written. GitHub reports MERGEABLE, mergeStateStatus BLOCKED by review.

Verdict: APPROVE. The r11 blocking item is fixed and the rebase preserved the branch. The remaining items are optional.

@eric8810
eric8810 merged commit 508d699 into main Nov 26, 2026
eric8810 added a commit that referenced this pull request Nov 26, 2026
Base-1 (#2174) landed `xtask/access-layer.json`, and this branch removes
`Session::service_opt`; the listed entry no longer has a definition, so
`xtask-check` would report it as listed one and found none.

Refs #2032
@yyhhyyyyyy yyhhyyyyyy mentioned this pull request Nov 28, 2026
3 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants