mirror of
https://github.com/mudler/LocalAI.git
synced 2026-11-04 03:24:43 -05:00
* Store the folder and its mode on a saved agent
A saved agent gets FolderID, the workspace node of its folder, and
FolderMode, read or write. The folder is kept by node so that a rename
or a move is followed. A mode without a node is an agent whose folder
is not chosen yet; Validate accepts it, and refuses a node without a
mode.
The GORM store adds two columns with defaults, so AutoMigrate fills
the rows of existing agents as agents without a folder. The JSON store
reads a file without the keys the same way. Both stores pass the new
contract case.
Assisted-by: Claude:claude-opus-5-5
* Keep on a chat whether its saved agent had a folder
A chat whose agent is deleted runs today without the agent's grants.
When that agent had a folder, nothing is left to say which folder the
chat may read, so the chat must be refused instead of getting the whole
home. ChatRecord.ScopedAgent records that the agent had a folder.
CreateChat writes the flag and SetScopedAgent changes it. UpdateChat
leaves it alone, like the tool switches, so the loop's stale copy of
the record cannot clear it. Both chat stores read chats stored before
the flag as not scoped; the GORM column has a default, so AutoMigrate
is the migration.
Assisted-by: Claude:claude-opus-5-5
* Add the design and plan for agent folder scope
A saved agent works on the whole home folder of its user. The spec
lets the user give an agent one folder and a mode, read only or read
and write, and confines every chat that runs it to that folder.
The workspace store enforces the folder through a fence on the actor,
so a caller that forgets it gets less access, not more. The spec maps
every caller that builds a user actor today, including the host bash,
the sandbox runner and the add-on workspace operations, and how each
is moved to the chat's access.
The plan splits the work into ten lanes; the store fence and the agent
record come first.
Assisted-by: Claude:claude-opus-5-5
* Resolve the folder of a saved agent by node
A person chooses an agent's folder by its path in their home; the
agent keeps the node, so a rename or a move is followed. The new
FolderResolver turns the path into the node and back, always as the
user. A path is refused when it is not a live folder, when it is
LocalAI/ or Chats/ or inside them, or when it names a parent. The
home itself ("/") is allowed.
The workspace stores cannot find a node by its ID yet. PathOf reads
the newest change sets of the home first, checks the path it finds
with Stat, and else lists the folders the user can read. A store that
implements NodeByID is used instead. Nothing is cached, so every
frontend answers the same.
SaveAgent keeps the stored folder when it replaces an agent, so a
caller that knows nothing of folders cannot widen one.
SaveAgentWithFolder sets or clears it. ImportAgent looks the folder of
a file up in the importer's home, and saves a folder that is not there
as unset: the mode without a node, which does not start.
Assisted-by: Claude:claude-opus-5-5
* Add a fence to the workspace actor
A chat whose saved agent has a folder must reach only that folder and
the chat's own folders. The store needs to know which folders those
are on every call, so the actor carries them.
Actor.Fenced returns a copy that reaches only the given folders, by
node ID, each at most at its mode. The fence is an unexported field:
a copy of the actor keeps it, and only Fenced can set it. Fencing a
fenced actor adds a layer, and a node is reached only when every
layer allows it, so a fence never grows.
The helpers in export.go let both store implementations apply the
same rules: the mode a fence allows on a node, its roots, and the
limit of MaxFenceRoots roots per call.
Assisted-by: Claude:claude-opus-5-5
* Show and choose the folder of an agent in the API
The agent routes carry folder. A write takes {path, mode}: the server
turns the path into the folder's node, and refuses with 400 a path
that is not a folder of the user's home, or is LocalAI or Chats. A
write without folder keeps the agent's folder, so a client that does
not know the field cannot widen the agent; {path: ""} clears it. A
read answers the folder's path now, its name, the mode and a state:
ok, missing or unset. The node never leaves the server.
An agent with a folder exports as version 2, with the folder's path
and mode. A server that reads only version 1 refuses that file, so a
scoped agent is never imported elsewhere as one with all the files.
An agent without a folder still exports as version 1. The import
reads both versions and looks the folder up in the importer's home;
a folder that is not there saves the agent as unset, with a warning.
The Swagger spec, the API instructions and the agents docs page show
the field and the new file version.
Assisted-by: Claude:claude-opus-5-5
* Enforce the actor fence in both workspace stores
The store is the one place every file call of a chat goes through, so
it applies the fence: a caller that forgets the agent's folder gets
"not found", never the whole workspace.
- The mode of a fenced actor on a node is the lower of its grants and
the fence. A root in the Trash counts for nothing, and is back after
Undo, because the fence holds the node ID.
- A fenced actor never takes the administrator shortcut, so it cannot
grant, revoke or list grants, and ReadablePrefixes gives only fence
roots or folders inside them.
- A root cannot be deleted, moved or renamed by the fenced actor, by
any path: Move, Delete, Undo, an upper layer, or a delete of a folder
above a nested root.
- A fence with too many roots or a bad root is ErrInvalid.
The shared suite in wstest runs the new specs against the JSON store
and the GORM store (SQLite and PostgreSQL).
Assisted-by: Claude:claude-opus-5-5
* Map the model's paths through the chat's place
A chat's file tools spelled every path as a path in the user's home.
A chat whose agent has a folder sees that folder at /workspace/home and
its own chat folder at /workspace/chat, so the mapping must come from
the mounts of the chat's view, not from the principal.
session.Place maps a path the model writes to a workspace path: "/x",
"x", "home/x" and "/workspace/home/x" are x in the primary mount,
"/workspace/<name>/x" is x in the mount of that exact name, and the
skill layers keep their names. It refuses "..", NUL, control characters
and invalid UTF-8 wherever they point, and a /workspace path that is no
mount. Encoded and look-alike separators stay part of a name. Place is
only a mapping: the store's fence enforces the access.
session.Access holds a turn's actor, view and place. It has no exported
fields and one constructor, so a tool cannot be built from a principal
string. Owner gives the user's own actor without the fence.
Assisted-by: Claude:claude-opus-5-5
* Build a chat's view from its folders and describe it
BuildView took the home of the principal as the folder at
/workspace/home. A chat whose agent has a folder needs that folder
there, at the agent's mode, and its own chat folder beside it.
BuildView now takes the primary folder and the chat folder. The chat
folder is mounted at /workspace/chat, read and write; the name chat is
reserved like the skill layer names. The store caps each mount at the
actor's mode, and a fenced actor gets the shared folders read only.
Every caller passes the home and no chat folder, so an unscoped chat
keeps today's view.
LayoutPrompt takes a ScopedPrompt. A scoped chat hears only of its
folders: the agent's folder by its name and mode, with a line that it
cannot see the user's other files, the chat folder and where its
working files go, and the shared folders. It gets no hint to build a
page, because pages live outside its folder. An unscoped chat keeps
today's text.
Assisted-by: Claude:claude-opus-5-5
* Find a workspace node by its ID
A caller that keeps a node ID, such as the folder of a saved agent,
had no way to ask the store where that node is now. It had to search
the journal and then list folders, which costs one query per folder
in a large home.
Store.NodeByID returns a live node at its current path, so a rename
or a move of the node or of a folder above it is followed. It answers
ErrNotFound when the node or a folder above it is deleted, and when
the actor cannot read it; a fenced actor finds only nodes inside its
fence. Both stores implement it and the shared suite checks it. The
remote store of the Sandbox add-on refuses it, like its other calls.
Assisted-by: Claude:claude-opus-5-5
* Name the work folder of a scoped chat at /workspace/chat
A chat whose agent has a folder keeps its chat folder in the home, but
sees it as a mount of its own at /workspace/chat. Its work folder is
then /workspace/chat/work, not a path under /workspace/home.
workfiles reads /workspace/chat as the chat folder: a helper file under
its work folder is working, a script beside the attachments is a stray
helper, and a folder named chat in the agent's folder is an ordinary
folder. ScopedPrompt steers the model to that work folder and sends the
deliverables to the agent's folder, or to the chat folder when the
agent may only read. It says nothing of pages or of the settings
folder, which are outside the agent's folder. The chat picks the text
by its view.
Assisted-by: Claude:claude-opus-5-5
* Look up the folder of an agent by node
The folder resolver searched the journal of the home and then listed
folders to find where an agent's folder is now. The stores can now
find a node by its ID, so the resolver asks them directly and the
search is gone.
Assisted-by: Claude:claude-opus-5-5
* Resolve the file and media tools through the chat's access
The file tools mapped paths to the user's home and acted as the chat's
actor, and the media tools did the same through files.HomePath. A chat
whose agent has a folder must reach only its folders, and search must
start in the agent's folder, so the count of documents still being
indexed cannot count files elsewhere in the home.
files.Service.Tools and media.Service.Tools take a session.Access. Every
path goes through its place and every call acts as its actor. A write
to a read-only folder is refused before the store sees it. A search
with no path starts at the primary folder, and in a scoped chat also
looks in the chat folder; the pending count is taken below that root.
files.HomePath is removed.
UnscopedAccess builds today's access of a chat (the home and the
shared folders), and the studio service takes the turn's access from
one function, turnAccess, which gives that access until the chat
access resolver replaces it.
The new specs run the paths that try to leave the folder (parents,
absolute and doubled paths, encoded and look-alike separators, NUL,
other cases) through every file tool and the media tools, and check
that nothing outside the folder is read, named or changed, and that
search counts no pending file outside it.
Assisted-by: Claude:claude-opus-5-5
* Resolve the access of a chat at every turn
A chat whose saved agent has a folder must reach only that folder. Up
to now every chat got the user's actor, which reaches the whole home.
The chat's access is now resolved from the stores at every turn
start. With no agent folder it is the actor and the view of today.
With a folder the actor is fenced to the agent's folder at its mode,
the chat's own folder read and write, and the shared folders and the
skill layers read only; the chat's folder is made before the fence,
because a fenced actor cannot make it. A sub-agent takes the folder
of its parent's agent, and its own agent's folder inside it.
A folder that is deleted, unreadable or not chosen refuses the chat
with ErrAgentFolderMissing; it never falls back to the whole home.
A chat records whether its agent had a folder, so a chat whose agent
was deleted is refused too. CreateAs refuses such an agent at once.
session.Access carries the actor and the view, has no exported fields
and one constructor. Open takes it, the turn tools are built from it,
and an open chat compares the fence as well, so an edit of the agent
restarts the harness at the next turn on any frontend. The person's
uploads and renames use the owner's actor, without the fence. The
files a command changed are read as the chat can read them.
Nothing is kept between turns, so frontends cannot disagree.
Assisted-by: Claude:claude-opus-5-5
* List a scoped chat's files by its place in the prompt
The turn prompt lists the chat's files with the paths the model uses.
For a chat whose agent has a folder those paths come from its mounts,
and a file the chat touched outside its folders, for example before
the agent got a folder, must not be named.
Manager.FilesIn is Files with a place. For a scoped place, each file
is named by its mount (/workspace/home for the agent's folder,
/workspace/chat for the chat folder) and a file outside every mount is
left out. Other places give what Files gives. The prompt's file list
uses the turn's place; the chats API keeps the user-wide list.
Assisted-by: Claude:claude-opus-5-5
* Answer 409 when an agent's folder is missing
A chat with a saved agent whose folder is missing or not chosen does
not start. The chat endpoints now say so with 409 and the type
agent_folder_missing, both when the chat is created and when a
message is sent to an open chat, instead of a server error.
The agent docs say what a chat with a folder reaches, when a change
of the folder applies, and that nothing is kept between turns.
Assisted-by: Claude:claude-opus-5-5
* Point a scoped chat at rules and work folders in its own folders
The rules nudge walked from the chat folder up to the home root and
named AGENTS.md files there, and the stray-helper note named the work
folder under /workspace/home. A chat whose agent has a folder must hear
only of its own folders.
The nudge takes the turn's access: it reads paths through the place,
starts at the primary folder (the agent's folder) and stops there, so
it never points above the folder or into the chat folder mount. The
helper note names /workspace/chat/work/ in a scoped chat, and a
sub-agent of a scoped parent gets the scoped work folder text.
Assisted-by: Claude:claude-opus-5-5
* Find workspace actors built outside the chat access
An actor built from a principal has no fence and reaches the whole
home. A spec now parses the studio service, the command runners, the
add-on host operations and the application wiring, and fails on a
workspace.Actor literal, a files.UserActor call or an Actor(principal)
call in a function that is not on the allowlist. Each allowed entry
says why: a host read of the user's settings, a user surface, or a
caller that a later change moves to the chat's access. An entry that
builds no actor any more fails the spec too, so the list stays exact.
Assisted-by: Claude:claude-opus-5-5
* Build the expected view of a chat with the view's folders
The spec of a chat without an agent folder compared its view with
BuildView called with the old arguments, so the test package did not
compile after the merge of the view builder. It now passes the home
as the primary folder and no chat folder, which is the view of an
unscoped chat.
Assisted-by: Claude:claude-opus-5-5
* Give every file tool of a turn the chat's resolved access
The resolver of a chat's access built the view of a scoped chat
itself, with no shared folders, while every other chat got its view
from the session manager. And the file tools, the media tools, the
chat's file list in the prompt, the rules nudge and the work folder
lines each asked for an access of their own, the view of the whole
home. A chat whose agent has a folder therefore had a fenced actor
but home-relative paths: it reached its folder only through paths
such as /Projects/Acme/a.txt, and its prompt named the home.
The session manager now builds every chat's view: UserAccess mounts
the home, and the new ScopedAccess mounts the agent's folder at home,
capped at the fence's mode, the chat folder at chat and the shared
folders read only. It refuses an actor without a fence, and a folder
outside the fence is an error, never a view of the home. The
resolver calls it with the innermost folder, so a sub-agent of a
saved agent still works in its own folder.
The access that the resolver builds once at the start of the turn
now goes down to every consumer. A sub-agent of a saved agent acts
for its parent chat with the same access (Access.ForChat), and a
generic sub-agent gets its tools from the parent's access. The seam
that gave the unscoped access, and the files service's own view
builder, are removed, so a new consumer cannot build a view by
mistake. A turn whose access has no folder gets no tools rather than
the home.
A scoped chat now sees its folder at /workspace/home and its chat
folder at /workspace/chat in its tools, its search, its prompt and
its work folder lines. A chat whose agent has no folder is unchanged.
Assisted-by: Claude:claude-opus-5-5
* Find chat views built outside the chat access
The turn's access is resolved once and handed down, but nothing
stopped new code from building a view of its own, which shows a
scoped chat the whole home. A second scan now parses the same
sources as the actor scan and fails on a call of BuildView,
SkillLayerMounts, NewAccess, UserAccess or ScopedAccess, or on a
store's View, in a function that is not on its allowlist. The
resolver is the one allowed caller; the host bash, the sandbox
runner and the add-on host operations are listed until they take
the chat's access. A stale entry fails the scan too.
Assisted-by: Claude:claude-opus-5-5
* Keep a sub-agent inside its parent's folder
A saved agent started from a scoped chat could name a folder
outside the chat's own, and the child was made before its first
turn failed with a message about a missing folder. spawn_agent now
checks the agent against the chat's agent from the stores before it
makes the child: no folder is fine, the same folder or one inside
it is fine, anything else fails with "this agent works in another
folder than this chat". The child never has more reach than its
parent, in folder or in mode.
The ScopedAgent flag of a sub-agent was reset to what its own
agent had at each turn. A child of a scoped chat with an agent
without a folder lost the mark, so deleting the parent's agent
would have given that child the whole home. The flag now follows
both folders.
New specs cover a generic child, a saved-agent child outside,
inside and at the parent's folder with the lower mode, a child
without a folder, and the work folder wording of a child of a
read-only or read-write parent.
Assisted-by: Claude:claude-sonnet-5-5
* Show agent folders in list_agents and limit them by scope
list_agents gave a scoped chat every saved agent, including ones
that spawn_agent would refuse, and told the model nothing about
where an agent works. Each entry now carries the name of the
agent's folder and its mode, or folder_missing when the folder is
deleted or not chosen. The path is left out, since it would show
the folders above the chat's own. A chat whose agent has a folder
lists only the agents that fit under that folder, by the same check
spawn_agent makes.
The docs for saved agents as sub-agents and for the agent folder
describe both.
Assisted-by: Claude:claude-sonnet-5-5
* Keep the triggers of a scoped agent to its folder
A chat of an agent with a folder reaches only that folder, but its
triggers still worked on the whole home. A file trigger could watch
any folder, the rules of a run were read from the home root down
with the user's actor, the first message named home paths, and a run
whose agent's folder was gone fell through to a failed chat start
after the host had already read the home's rules. The trigger tools
of a scoped chat could also list, change or propose triggers that
reach the whole home.
The agent's folder now bounds every step:
- Saving a file trigger (create, update, edit, confirm) refuses a
folder outside the agent's folder, and a trigger of an agent whose
folder is missing or not chosen.
- Each run checks the agent's folder before it reads anything. A
missing or unset folder skips the run with "the agent's folder is
missing" and switches the trigger off; a watched folder that is not
inside the agent's folder does the same with its own reason. No
chat is made and the owner is told.
- The folder check and the rules are read with an actor fenced to
the agent's folder, read only, so no AGENTS.md above it is read.
The rules of a schedule run start at the agent's folder. The first
message names folders and the file as the chat sees them, under
/workspace/home, and the rules nudge of the run's chat counts those
rules as given.
- In a scoped chat the trigger tools read folders as paths of the
chat's place, refuse one outside the agent's folder, and see only
the triggers of that agent.
The trigger watcher takes the service's administrator actor, made
once next to the change feed's, and the trigger functions leave the
actor scan's allowlist.
Assisted-by: Claude:claude-opus-5-5
* Send connector replies through the chat's access
The files a connector reply sends were listed from every change made
in the chat's name and read with the user's actor, so a reply of an
agent limited to one folder could send a file from anywhere in the
home that some host-side write had attributed to the chat. A message
to an agent whose folder was missing made or reopened a chat, failed
to start it, and answered with a generic error.
A reply now resolves the chat's access once, lists the turn's files
through its place (a file outside the chat's folders is left out)
and reads each one with its fenced actor. A file the access cannot
reach is skipped without being named. Before it makes a chat, a
message checks the bound agent's folder; when it is missing or not
chosen, the sender gets one reply, "This agent cannot work right
now: its folder is missing.", the refusal is logged and the binding
stays on. The same reply covers a folder that goes away between the
check and the turn. readChatFile leaves the actor scan's allowlist.
Assisted-by: Claude:claude-opus-5-5
* Name a read-only refusal of a commit by its guest path
The store names an upper entry that a read-only mount refused by
its path in the view (/home/x), not by its store path. The note
that a command's output ends with took every path but an
outside-view one for a store path, so it told the model that
"/home/x was not saved", a path the guest does not have. A path
that no mount holds but that starts with a mount name is now taken
as a path of the view and gets the /workspace prefix.
Assisted-by: Claude:claude-opus-5-5
* Take the actor and view of command runners from the chat's access
The host bash and the sandbox runner made their own actor and view:
the host bash a user actor from the principal and the view of the
whole home, the sandbox runner a plain actor by default and the view
from its own mount requests. Neither knew the chat's agent folder,
so a command of a scoped chat could reach the whole home.
The runner now has no default actor or view. Options.Actor takes a
context and returns an error, and Options.View returns the view
itself; both are asked at every call. A view of another actor than
the chat's is refused, and a sandbox whose actor or mounts changed
is made again, so an agent's new folder or mode applies from the
next command. A failing resolver fails the call, also with a sandbox
running.
The server wires both hooks to the chat's resolved access: the new
Service.CommandActor and Service.CommandView, the latter refusing an
actor that is no longer the chat's. Access.SandboxView adds the skill
layers to the turn's view, at the names the file tools use. The host
bash refuses a fenced actor, at the tool and again at each call, as a
command on this machine reads what the server can read. The Sandbox
add-on passes a label actor and its home view: the host binds each
workspace operation to the call's chat.
The lane 5 entries leave the actor and view scan allowlists.
Assisted-by: Claude:claude-opus-5-5
* Offer no host bash to a chat whose agent works in one folder
A command of the built-in bash runs on this machine and reads every
file LocalAI can read. No workspace rule confines it, so a chat whose
agent works in one folder cannot have it, whatever chats_host_exec
says. The tool's build now refuses a fenced actor, so the chat gets
no bash, its prompt says nothing runs commands, and the shell group
of the Tools menu gives the reason: the agent works in one folder
and runs commands only in the Sandbox add-on. Sub-agents of such a
chat have the fenced actor too.
The docs of saved agents and of the commands on this machine state
the rule and the Sandbox layout of a scoped chat.
Assisted-by: Claude:claude-opus-5-5
* Tell a scoped chat where its Sandbox commands start and what they keep
The commands block of the prompt told every chat with the Sandbox
that a command starts in /workspace/home, the user's home, and that
what it saves there or in a writable shared folder is kept. In a
chat whose agent works in one folder, /workspace/home is that folder,
the chat folder is /workspace/chat and the shared folders are read
only. The block now says so, and with a read-only folder it names
only /workspace/chat as kept.
Assisted-by: Claude:claude-opus-5-5
* Name a scoped chat's attachments where its commands see them
The model learns of an attached file by its guest path, which was
always /workspace/home/Chats/<chat>/<file>. In a chat whose agent
works in one folder, /workspace/home is that folder: the file and
media tools still found the file through the place's chat alias, but
a command sees the chat folder only at /workspace/chat, so the path
named nothing for it.
The text the model gets now names a file of the chat folder at
/workspace/chat/<file> in a scoped chat, through the chat's place:
when a message is sent, queued or injected, in the summary of the
chat, and in the model state rebuilt after an edit, a regenerate, a
fork or an import. What is stored keeps the home spelling, which
SplitMessage reads back, and an unscoped chat is unchanged.
Assisted-by: Claude:claude-opus-5-5
* Remove the duplicated allowlist entries of the actor scan
Assisted-by: Claude:claude-opus-5-5
* Read and write the folder of an agent in the agent helpers
The agent API now answers an agent's folder with its path, mode and
state, and a write keeps the stored folder unless it names one. The
page helpers learn that shape: the folder field of a save is sent only
when the person changed it, an empty path clears it, a missing or
unset folder that the person did not replace is kept, and the mode is
read unless write was chosen. Small helpers say whether a listing
entry can be chosen (not a folder LocalAI manages, not a shared
folder), which folders agents use for the Files page marker, and
whether a chat error is the missing-folder conflict.
Assisted-by: Claude:claude-opus-5-5
* Move the folder walk of the Move dialog into a folder picker
The agent editor needs the same walk through the person's folders as
the Move dialog, so the breadcrumb and the folder list move into
FolderPicker, with their styles, and the Move dialog draws it. The
picker can show a folder as one that cannot be chosen, with the
reason next to it, and a folder that cannot be read now offers to try
again; a folder still loading says so instead of an empty list.
Assisted-by: Claude:claude-opus-5-5
* Choose the folder of an agent in the agent form
The agent form gets a Files section after the instructions: All my
files, or One folder chosen in the folder picker, and whether the
agent's chats can read the folder or read and change it. The picker
shows the folders LocalAI manages as ones that cannot be chosen, and
Home itself can be chosen. A folder that was deleted, or an imported
agent whose folder was not found, is said in place with an offer to
choose another; the rest of the form still saves and keeps it.
A save sends the folder only when the person changed it, so editing
another field never touches it. Picking One folder and choosing
nothing stops the save, as it would otherwise save an agent on all
the files. The Export section now downloads the file the server
writes, which names the folder, and says so.
Assisted-by: Claude:claude-opus-5-5
* Show the folder of an agent on the agents list and its page
An agent with a folder shows it in the list's line and on its page,
with its access in words and a lock when its chats can only read it.
A folder that is gone, or an agent with no folder chosen yet, shows
a warning that opens the form; the agent's page also says so above
its facts and offers to choose another folder.
Assisted-by: Claude:claude-opus-5-5
* Mark the folders that agents work in on the Files page
A folder that a saved agent works in gets a small marker with the
agent's name, or the number of agents, and a tooltip that names each
one with its access. Inside such a folder, a line over the list says
the same. The page reads the agent list it can already fetch, so the
files API is unchanged, and the page still shows all the files.
Assisted-by: Claude:claude-opus-5-5
* Show a chat's folder and say when its agent's folder is missing
A chat with an agent that has a folder shows the folder next to the
agent in the message box, with a lock for read only, and the Tools
menu says which files the chat's tools reach. When the folder is
gone, the chip says so and opens the agent's form.
A chat whose agent's folder is missing does not start, and the server
answers with a conflict. The message box now says that in plain words,
keeps the message, and offers Edit agent, instead of the server's
text.
Assisted-by: Claude:claude-opus-5-5
* Test the folder of an agent across the web interface
The agent stubs now list folders by path, read a written folder back
as the server does, export a version 2 file for an agent with a
folder, import one whose folder is not found as unset, and refuse to
start a chat whose agent's folder is missing.
The specs choose a folder and see it on the list, switch the access,
leave an unchanged folder out of the save, clear it, keep and replace
a missing folder, keep Chats and LocalAI out of the picker, retry a
folder that cannot be read, see the Files marker, the chat's chip and
Tools line, the missing-folder chat error with Edit agent, and the
import warning. A render smoke opens the picker on the real server,
and one spec checks that the copy names no internal path.
Assisted-by: Claude:claude-opus-5-5
* Describe the agent's folder in the web interface
The agent docs said what the folder field does in the API. They now
also say where the web interface sets it, how the agents pages, the
Files page and a chat show it, and what a chat whose folder is
missing offers.
Assisted-by: Claude:claude-opus-5-5
* Record the chat an add-on call was made for
An add-on's workspace operations run as the user of the live request,
with no idea which chat made it. Only an action carries a chat, and
only as a key in its resource ID; a read tool such as the Office
add-on's read-docx carries none. So a chat that should reach only one
folder could reach the whole home through an add-on.
The in-flight record of a request now keeps, next to the envelope, a
binding to the chat the request was made for: the user's principal
and the chat ID. It is host-side only and never a field of the
envelope, which installed add-ons decode with unknown fields refused.
A context carries the binding from the chat turn to the place that
records the request. The broker gives each host operation the chat
and the scope of its live request. An operation ID that requests of
two chats share is not live, so neither chat is trusted.
Assisted-by: Claude:claude-opus-5-5
* Keep the chat binding of a runtime call on the host
The runtime client records each call's envelope for the host operation
channel. It now records the chat binding too when the call's context
carries one, so the add-on's host operations know which chat made the
request. The envelope sent to the add-on is the same bytes with or
without a binding: a spec checks that the body of a bound call equals
the body of an unbound one and still decodes with unknown fields
refused.
Assisted-by: Claude:claude-opus-5-5
* Carry the chat binding in a forwarded add-on request
A frontend that is not the add-on owner forwards an add-on call in a
signed request. The chat the call was made for now rides in that
request as a signed field, chat, and the owner puts it back on the
context of the call it serves, where the runtime client records it.
A changed, added or removed binding fails the signature check, and a
signed but incomplete one is refused. A request that no chat made has
no chat field and signs as before.
An owner that does not know the field refuses a forwarded call that a
chat made, so the owner must be upgraded before the frontends.
Assisted-by: Claude:claude-opus-5-5
* Bind every add-on tool call of a chat to the chat
The chats consumer ran an add-on tool with the conversation ID only,
which the owner used to resolve a selection and, for an action, as the
key of the add-on's state. Nothing told the host which chat a read
tool or a change came from.
The tool adapter now has ExecuteChat, which takes a ChatCall (the
chat's user and ID, from the chat turn's own record) and binds the
call to the chat on the host side for every tool kind: a read with no
resource, an action, and a change made at once. The chats adapter
refuses a call that names a conversation without that binding, so a
chat's call cannot be made unbound by mistake. Other consumers, such
as the OpenAI-compatible route, keep calling without a binding.
Assisted-by: Claude:claude-opus-5-5
* Run add-on workspace operations with the chat's access
The workspace operations of add-ons (materialize, commit, changes,
export and import) worked on the whole home of the request's user. A
chat whose agent has a folder could therefore read and write any file
through the Office or Sandbox add-on.
They now resolve their access from the chat binding of the live
request, through a new Access hook that the chats service answers
(Service.AddonAccess). A chat's call gets the chat's access, as its
file tools do: in a chat whose agent has a folder, the add-on's "/" is
that folder, /workspace/chat names the chat folder, the agent's mode
applies, and paths resolve through the chat's place, so a parent
reference is refused and an encoded separator is part of a name. The
mounts go through Access.SubView, which builds a view only inside the
access, for its fenced actor. When an add-on mounts its "/" at home,
the host adds the chat folder at chat, so the Sandbox sees the chat's
layout without a change. Changes list only what the access may read,
and a commit entry outside the view is a conflict.
A call whose chat cannot be resolved is refused and never runs
user-wide. An action request without a binding is resolved by its
chat key, as before, and refused when it names no chat. A call that
no chat made (an add-on page, the OpenAI-compatible route) still works
on the whole home, through Manager.PersonAccess.
The four lane 6 entries leave the actor scan and the view scan.
PersonAccess joins the view scan's matcher, with AddonAccess as its
one allowed caller. An end-to-end spec runs the real Office and
Sandbox add-ons in a scoped chat.
Assisted-by: Claude:claude-opus-5-5
* Build the chat access of the file index route test
files.Service.Tools takes a session.Access since the chat access
change, so the route test of the text index passed a bare actor and
its package did not compile under the auth tag.
The test now builds the access as the chats service does for a chat
whose agent has no folder: the user's home as the primary folder of
the view, then session.NewAccess. The assertions are unchanged.
Assisted-by: Claude:claude-opus-5-5
* Test the folder of an agent through every surface of a chat
The specs of the folder feature each test one surface. This suite
runs one chat of an agent limited to a folder through all of them at
once, on an indexed SQL workspace: the file and media tools, the search
and its pending count, a command of the Sandbox in a fake sandbox, a
read call and an action call of an add-on through the real workspace
operations bound to the chat, a generic and a saved sub-agent, the
trigger tools, a file trigger run, a connector reply, a renamed folder,
a mode change, an edit that narrows the folder (also seen by a second
frontend) and a deleted folder.
The files outside the folder hold a token that the scripted model never
writes. After each spec the suite collects every text a person or a
model can see: tool results and errors, prompts, messages, transcripts
with their cards, live events, chat file lists, tool panels,
notifications, connector replies and files, the add-on's data directory
and the connector log. The token must be in none of them, and the files
outside must be unchanged.
A control spec runs the same probes from an agent without a folder and
checks that they do find the token, so the probes and the collection
cannot pass by seeing nothing.
Assisted-by: Claude:claude-opus-5-5
* Complete the docs of the folder of an agent
Each change of the folder feature documented its own part. This
makes the pages one account of it:
- Saved agents: the missing and unset states in one bullet, what the
folder does not limit (MCP servers, web tools, collections, pages),
that the Files page stays user-wide, when an edit applies, the
downgrade caveat, and the folder as a stateless row of the cluster
table. The Sandbox of a scoped chat mounts the agent's folder and the
chat folder only, as the add-on asks for them; the page said it also
had the shared folders and skills.
- Chats: the chat folder at /workspace/chat for the model, sub-agents
of a scoped chat, and commands only in the Sandbox.
- Add-ons: the Sandbox and Office sections say what / is in a chat whose
agent has a folder.
- First agent: the optional folder step and the "Folder missing" case.
Assisted-by: Claude:claude-opus-5-5
* Draft the PR description and release note of agent folders
No release notes file exists for the next release yet, so the draft
text lives next to the spec and the plan. It carries the release note
paragraph with the downgrade caveat and the upgrade order of a cluster.
Assisted-by: Claude:claude-opus-5-5
* List the chat binding specs in the per-report add-on inventories
The chat binding change added five specs to the gateway and runtime
packages and named them in the case lists of the gateway, artifacts and
apps suites. These three suites also keep one case list per Ginkgo
report, and the verifier compares each report with its own list. The
new names were missing there, so the three suites failed with an
inventory mismatch.
A dry run of every Ginkgo suite's commands now lists the same It names
as each report's inventory, in both directions.
Assisted-by: Claude:claude-opus-5-5
* Hide stale paths from a fenced actor's history
A folder moved into a fence makes its parent identities readable.
Their historical paths can still name locations outside the fence.
Hide each historical side when its readable parent's current path
differs. Reuse the generic title when filtering hides a side. Keep
the journal and unfenced history unchanged so Undo uses identities.
Assisted-by: nib:gpt-6.1-sol
* List the chat binding cases in Tables tools
The Tables tools runner includes every adapter spec in its output.
List the four chat binding cases so the exact inventory accepts them.
Assisted-by: nib:gpt-6.1-sol
* Keep shared agent folders unset in exports
A followed folder outside the home cannot round-trip through a home path.
Export its mode with an empty path so import warns and stays fail-closed.
Responses keep public shared paths without exposing other internal paths.
Distinguish deleted scoped agents from unscoped agents in the guidance.
Assisted-by: nib:gpt-6.1-sol
* Refuse scoped chats over the folder limit
Keep every required shared root in each intersecting fence. Refuse
creation and turn access when the complete set exceeds 32 roots.
Reserve a chat root before its folder exists and fence listings empty
on refusal. Propagate shared enumeration failures instead of omitting
roots.
Map capacity refusals to a fixed 409 response and give connectors a
safe capacity message. Check boundaries, retries, background access,
and HTTP handlers with focused regressions.
Assisted-by: nib:gpt-6.1-sol
* Verify unset imports refuse chat startup
Assert the folder-specific refusal without a harness start or saved chat.
Clarify public response paths and unset exports in the API metadata.
Assisted-by: nib:gpt-6.1-sol
* Keep the folder retry test under user control
A background refresh consumes the one-shot successful response before
this test observes its load error. Isolate the mocked Files page from
the live workspace stream and agents list. Keep reads failing until
the error assertions pass, then allow the actual Retry click to recover.
Check that Retry reads again and removes the error, without changing
the existing assertions or their timeouts.
Assisted-by: nib:gpt-6.1-sol
* Test and document folder capacity refusals
Use the existing Ginkgo suites for capacity regressions. Exercise a
successful turn, refusal after shares change, and a retry through a
second service on the same stores. Check that refusal leaves no claim
or pending message.
Verify that connectors send one fixed refusal and that triggers stay
enabled after capacity failures. Document the 32-root budget and the
all-required-roots-or-refuse contract.
Assisted-by: nib:gpt-6.1-sol
* Control crashes in the restart budget test
The crash fixture exits after 100 ms, before startup necessarily finishes.
A busy runner can fail the readiness handshake instead of testing restarts.
Start a normal fixture and kill each published incarnation explicitly.
Keep the exact restart count and persistent failed-state assertions.
Assisted-by: nib:gpt-6.1-sol
* Check capacity test cleanup errors
Assert service and workspace cleanup through Ginkgo. Keep service cleanup before workspace cleanup and report close failures instead of discarding them.
Assisted-by: nib:gpt-6.1-sol
---------
Co-authored-by: Ettore Di Giacinto <mudler@localai.io>
1373 lines
40 KiB
Go
1373 lines
40 KiB
Go
package session
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"path"
|
|
"regexp"
|
|
"runtime/debug"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/mudler/LocalAI/core/services/studio/sandbox"
|
|
"github.com/mudler/LocalAI/core/services/studio/workspace"
|
|
"github.com/mudler/LocalAI/core/services/studio/workspace/workfiles"
|
|
)
|
|
|
|
// Message is what the user sends.
|
|
type Message struct {
|
|
Text string
|
|
// Note is the text read from the files, which only the model gets, such
|
|
// as a voice note's transcript or a document's text.
|
|
Note string
|
|
// Attachments are files saved already, such as those of a message that
|
|
// waited for a turn.
|
|
Attachments []Attachment
|
|
Files []Upload // stored in the chat folder before the turn starts
|
|
// Media goes to the model as parts of this message when the harness can
|
|
// take them. It is not stored: the files in Files are.
|
|
Media []Media
|
|
// Loop is set when a loop of the chat sends the message by itself.
|
|
Loop *LoopMark
|
|
// Directive is an instruction for the model that comes with this message
|
|
// only, such as the text of a skill the person invoked. The model gets it
|
|
// before the message; the transcript does not keep it.
|
|
Directive string
|
|
// Invoked is the command the person used, kept with the message in the
|
|
// transcript (Entry.Invoked).
|
|
Invoked *Invocation
|
|
// Goal marks a message the server sends by itself to go on with the
|
|
// chat's goal. The transcript keeps it as a RoleGoal line of kind
|
|
// GoalLineContinue whose Rev is GoalTurn, so it never reads as typed by
|
|
// the person; the model gets Text as a user message.
|
|
Goal bool
|
|
GoalTurn int
|
|
}
|
|
|
|
// withDirective puts the directive of a message before the text the model gets.
|
|
func withDirective(directive, text string) string {
|
|
if directive == "" {
|
|
return text
|
|
}
|
|
if text == "" {
|
|
return directive
|
|
}
|
|
return directive + "\n\n" + text
|
|
}
|
|
|
|
// Upload is one file that came with a message.
|
|
type Upload struct {
|
|
Name string
|
|
Body io.Reader
|
|
}
|
|
|
|
// Fixed texts of error events and of the checkpoint. They never carry the
|
|
// text of an internal error.
|
|
const (
|
|
reasonAgent = "The agent stopped because of an error."
|
|
// ReasonNotAllowed and ReasonQuota tell the user why the model refused.
|
|
ReasonNotAllowed = "The model refused the request: you are not allowed to use it."
|
|
ReasonQuota = "The model refused the request: your quota is used up or the server is busy."
|
|
reasonTranscript = "The transcript could not be saved."
|
|
reasonSave = "The chat could not be saved."
|
|
reasonRefresh = "The files you attached are not in the sandbox yet."
|
|
reasonCheckpoint = "The changes of this turn could not be saved."
|
|
maxPaths = 200
|
|
checkpointLimit = 5 * time.Minute
|
|
)
|
|
|
|
// Chat is one conversation. A chat is in one of four states:
|
|
//
|
|
// idle no turn; Send starts one
|
|
// running a turn runs; Send injects, Stop interrupts
|
|
// renaming SetTitle moves the chat folder; Send waits
|
|
// closed Close was called; Open on the same ID reopens it
|
|
type Chat struct {
|
|
m *Manager
|
|
id string
|
|
// accMu guards the access of the chat: the actor (with ChatID, fenced
|
|
// for an agent with a folder) and the view of the sandbox. Open replaces
|
|
// it when the access resolved for the turn differs (see syncAccess).
|
|
accMu sync.RWMutex
|
|
acc Access
|
|
harnessView workspace.View // the view that the harness prompt names
|
|
dir string
|
|
turnCtx context.Context // the context of the running turn; under mu
|
|
|
|
mu sync.Mutex
|
|
rec ChatRecord
|
|
hs HarnessSession
|
|
closed bool
|
|
running bool
|
|
renaming chan struct{} // non-nil while SetTitle runs; closed at its end
|
|
done chan struct{} // closed when the running turn loop ends
|
|
stopped bool // Stop was called in the running turn
|
|
cancel context.CancelFunc
|
|
pending []string // messages that arrived when the turn was ending
|
|
swapping bool // the harness is being swapped inside the turn; under mu
|
|
// injectMu keeps a swap from closing a harness while send injects into it.
|
|
injectMu sync.RWMutex
|
|
turn int
|
|
text strings.Builder // assistant text of the turn, not yet stored
|
|
// The reasoning of the current step, not yet stored. It stops growing at
|
|
// MaxReasoningBytes (reasonCut). reasonFirst is the time of its first
|
|
// delta.
|
|
reason strings.Builder
|
|
reasonCut bool
|
|
reasonFirst time.Time
|
|
|
|
evMu sync.RWMutex // emit and Events read; reopen replaces the bus
|
|
bus *eventBus
|
|
// endMu orders the end of a turn: turn_end is emitted before the next
|
|
// turn can emit turn_start.
|
|
endMu sync.Mutex
|
|
|
|
// hostMu guards host, the host-side tools of the chat (see applyChatTools).
|
|
hostMu sync.Mutex
|
|
host hostTools
|
|
|
|
// cardMu guards cards, the tool cards that wait for their tool_end event.
|
|
cardMu sync.Mutex
|
|
cards []pendingCard
|
|
|
|
vmMu sync.Mutex // the sandbox: create, resume, suspend, destroy
|
|
vm vmState
|
|
lastUse atomic.Int64
|
|
tmu sync.Mutex
|
|
timer *time.Timer
|
|
|
|
persistMu sync.Mutex // one record write at a time, so an old copy never wins
|
|
// released is true while rec.HarnessState is dropped from memory (a
|
|
// closed chat). The state is in the store; persist keeps it there.
|
|
released bool
|
|
// stateSeq counts the changes of rec.HarnessState; savedSeq is the count
|
|
// that the store has.
|
|
stateSeq, savedSeq int
|
|
}
|
|
|
|
type vmState struct {
|
|
sb sandbox.Sandbox
|
|
busy int // tool calls in flight
|
|
unsupported bool
|
|
}
|
|
|
|
func newChat(m *Manager, x Access, rec ChatRecord) *Chat {
|
|
c := &Chat{
|
|
m: m, id: rec.ID, acc: x, rec: rec,
|
|
dir: m.chatDir(rec.ID), turn: rec.Turns, bus: newEventBus(),
|
|
}
|
|
c.lastUse.Store(time.Now().UnixNano())
|
|
return c
|
|
}
|
|
|
|
// idleForClose reports whether the chat is open, has no turn and was last used
|
|
// more than d ago.
|
|
func (c *Chat) idleForClose(d time.Duration) bool {
|
|
c.mu.Lock()
|
|
busy := c.closed || c.running || c.swapping || len(c.pending) > 0
|
|
c.mu.Unlock()
|
|
return !busy && time.Since(time.Unix(0, c.lastUse.Load())) > d
|
|
}
|
|
|
|
// access returns the actor of the chat, the owner's actor (no chat ID and no
|
|
// fence: the person's uploads and renames, in the chat folder only) and the
|
|
// view of the chat.
|
|
func (c *Chat) access() (actor, user workspace.Actor, view workspace.View) {
|
|
c.accMu.RLock()
|
|
defer c.accMu.RUnlock()
|
|
return c.acc.Actor(), c.acc.Owner(), c.acc.View()
|
|
}
|
|
|
|
// place is the place of the chat's access: how its tools name its files.
|
|
func (c *Chat) place() Place {
|
|
c.accMu.RLock()
|
|
defer c.accMu.RUnlock()
|
|
return c.acc.Place()
|
|
}
|
|
|
|
// modelText is the text the model of this chat gets for an entry.
|
|
func (c *Chat) modelText(e Entry) string { return ModelTextIn(e, c.place()) }
|
|
|
|
func (c *Chat) principal() string {
|
|
c.accMu.RLock()
|
|
defer c.accMu.RUnlock()
|
|
return c.acc.actor.Principal
|
|
}
|
|
|
|
// Events returns the channel of live events. A consumer that falls behind
|
|
// loses text events: the oldest go first, past a ring of 512. It loses
|
|
// reasoning events the same way, past a ring of 2048 of their own. Under a backlog
|
|
// of more than 10,000 events it loses tool_start and tool_end events too.
|
|
// turn_start, checkpoint, turn_end and error are never dropped. Close closes
|
|
// the channel. The transcript is the durable record: see History.
|
|
func (c *Chat) Events() <-chan Event {
|
|
c.evMu.RLock()
|
|
defer c.evMu.RUnlock()
|
|
return c.bus.ch
|
|
}
|
|
|
|
// emit queues an event. It never blocks. The caller must not hold c.mu.
|
|
func (c *Chat) emit(e Event) {
|
|
if e.Turn == 0 {
|
|
c.mu.Lock()
|
|
e.Turn = c.turn
|
|
c.mu.Unlock()
|
|
}
|
|
c.evMu.RLock()
|
|
b := c.bus
|
|
c.evMu.RUnlock()
|
|
b.push(e)
|
|
}
|
|
|
|
func (c *Chat) appendEntry(ctx context.Context, e Entry) int64 {
|
|
seq, err := c.m.o.Store.AppendEntry(ctx, c.id, e)
|
|
if err != nil {
|
|
c.m.log.Error("session: append entry", "chat", c.id, "error", err)
|
|
c.emit(Event{Kind: KindError, Text: reasonTranscript})
|
|
return 0
|
|
}
|
|
return seq
|
|
}
|
|
|
|
// persist stores the chat record. It returns the store's error: the caller
|
|
// decides what a failed save means. The in-memory record stays the newest, so
|
|
// a later persist retries the same data.
|
|
func (c *Chat) persist(ctx context.Context) error {
|
|
c.persistMu.Lock()
|
|
defer c.persistMu.Unlock()
|
|
c.mu.Lock()
|
|
rec := c.rec
|
|
rec.Updated = time.Now().UTC()
|
|
released := c.released
|
|
seq := c.stateSeq
|
|
c.mu.Unlock()
|
|
if released {
|
|
// A closed chat holds no harness state; do not overwrite the stored one.
|
|
cur, err := c.m.o.Store.GetChat(ctx, c.principal(), c.id)
|
|
if err != nil {
|
|
return fmt.Errorf("session: save the chat: %w", err)
|
|
}
|
|
// Only the time is ours: another frontend may have changed the rest.
|
|
cur.Updated = rec.Updated
|
|
rec = cur
|
|
}
|
|
if err := c.m.o.Store.UpdateChat(ctx, rec); err != nil {
|
|
c.m.log.Error("session: update chat", "chat", c.id, "error", err)
|
|
return fmt.Errorf("session: save the chat: %w", err)
|
|
}
|
|
c.mu.Lock()
|
|
c.rec.Updated = rec.Updated
|
|
if !released {
|
|
c.savedSeq = seq
|
|
}
|
|
c.mu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
func (c *Chat) snapshot() *sandbox.SnapshotRef {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if c.rec.Snapshot == nil {
|
|
return nil
|
|
}
|
|
s := *c.rec.Snapshot
|
|
return &s
|
|
}
|
|
|
|
// setSnapshot stores the reference of a suspended sandbox. When it returns an
|
|
// error the reference is not saved: the caller must keep the sandbox live and
|
|
// try again, or the snapshot would be lost on a restart.
|
|
func (c *Chat) setSnapshot(s *sandbox.SnapshotRef) error {
|
|
c.mu.Lock()
|
|
old := c.rec.Snapshot
|
|
c.rec.Snapshot = s
|
|
c.mu.Unlock()
|
|
if err := c.persist(context.Background()); err != nil {
|
|
c.mu.Lock()
|
|
c.rec.Snapshot = old
|
|
c.mu.Unlock()
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c *Chat) isRunning() bool {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
return c.running || c.renaming != nil
|
|
}
|
|
|
|
// startHarness starts the harness from the saved state. A state that the
|
|
// harness cannot read, or a missing state in a chat that has a transcript,
|
|
// starts a fresh session with the transcript in the system prompt.
|
|
func (c *Chat) startHarness(ctx context.Context) error {
|
|
c.primeChatTools(ctx)
|
|
c.mu.Lock()
|
|
rec := c.rec
|
|
c.mu.Unlock()
|
|
prompt := c.m.o.SystemPrompt
|
|
if prompt != "" {
|
|
prompt += "\n\n"
|
|
}
|
|
c.accMu.Lock()
|
|
view := c.acc.View()
|
|
c.harnessView = view
|
|
c.accMu.Unlock()
|
|
prompt += LayoutPrompt(view, PromptScope(view))
|
|
c.hostMu.Lock()
|
|
turnPrompt := c.host.prompt
|
|
c.hostMu.Unlock()
|
|
// The six sandbox tools exist only when there is a sandbox to run them in;
|
|
// without one they could only answer "cannot run commands".
|
|
tools := c.hostWrappers()
|
|
if c.m.o.Sandbox != nil {
|
|
tools = append(NewTools(c.acquireCreate), tools...)
|
|
}
|
|
actor, _, _ := c.access()
|
|
env := HarnessEnv{
|
|
SystemPrompt: prompt,
|
|
TurnPrompt: turnPrompt,
|
|
Tools: c.guardTools(tools),
|
|
Resume: rec.HarnessState,
|
|
Dir: c.dir,
|
|
Emit: c.onHarnessEvent,
|
|
Actor: actor,
|
|
}
|
|
if c.m.o.Inputs != nil {
|
|
env.Inputs = c.m.o.Inputs(actor)
|
|
}
|
|
var hs HarnessSession
|
|
var err error
|
|
if len(env.Resume) > 0 {
|
|
if hs, err = c.m.o.Harness.Start(ctx, env); err != nil {
|
|
c.m.log.Warn("session: the harness cannot read its saved state", "chat", c.id, "error", err)
|
|
env.Resume = nil
|
|
}
|
|
}
|
|
if hs == nil {
|
|
if sum := c.summary(ctx); sum != "" {
|
|
env.SystemPrompt += "\n\nThe conversation so far, from the transcript:\n" + sum
|
|
}
|
|
if hs, err = c.m.o.Harness.Start(ctx, env); err != nil {
|
|
return fmt.Errorf("session: start the harness: %w", err)
|
|
}
|
|
}
|
|
c.mu.Lock()
|
|
c.hs = hs
|
|
c.mu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
// summary renders the end of the transcript as plain text, at most 8 KiB.
|
|
// Checkpoints and reasoning are left out: the model never sees reasoning. The
|
|
// part before the last "context cleared" entry is left out too.
|
|
func (c *Chat) summary(ctx context.Context) string {
|
|
es, err := c.History(ctx)
|
|
if err != nil || len(es) == 0 {
|
|
return ""
|
|
}
|
|
es = SinceCleared(es)
|
|
var lines []string
|
|
size := 0
|
|
for _, e := range slices.Backward(es) {
|
|
if !ModelRole(e.Role) && (e.Role != RoleGoal || e.Note != GoalLineContinue) {
|
|
continue
|
|
}
|
|
l := e.Role + ": " + CapText(c.modelText(e), 1000)
|
|
if size += len(l) + 1; size > 8<<10 {
|
|
break
|
|
}
|
|
lines = append(lines, l)
|
|
}
|
|
slices.Reverse(lines) // collected newest first
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
|
|
// reopen revives a closed chat.
|
|
func (c *Chat) reopen(ctx context.Context) error {
|
|
c.mu.Lock()
|
|
if !c.closed {
|
|
c.mu.Unlock()
|
|
return nil
|
|
}
|
|
released := c.released
|
|
c.mu.Unlock()
|
|
if released {
|
|
// Close dropped the harness state from memory: load it again.
|
|
rec, err := c.m.o.Store.GetChat(ctx, c.principal(), c.id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// The whole record: another frontend may have run turns since.
|
|
c.mu.Lock()
|
|
c.rec, c.released, c.turn = rec, false, rec.Turns
|
|
c.mu.Unlock()
|
|
}
|
|
if err := c.startHarness(ctx); err != nil {
|
|
return err
|
|
}
|
|
c.evMu.Lock()
|
|
c.bus = newEventBus()
|
|
c.evMu.Unlock()
|
|
c.mu.Lock()
|
|
c.closed = false
|
|
c.mu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
// onHarnessEvent receives the events of the harness: text, tool calls and
|
|
// errors. The chat stores the transcript from them and adds the events of the
|
|
// turn itself.
|
|
func (c *Chat) onHarnessEvent(e Event) {
|
|
ctx := context.Background()
|
|
c.mu.Lock()
|
|
turn := c.turn
|
|
c.mu.Unlock()
|
|
e.Turn = turn
|
|
e.Change = nil // the chat alone emits checkpoints
|
|
switch e.Kind {
|
|
case KindReasoning:
|
|
if e.Text == "" {
|
|
return
|
|
}
|
|
e.Tool = nil
|
|
c.addReasoning(ctx, turn, e.Text)
|
|
case KindText:
|
|
c.flushReasoning(ctx, turn)
|
|
c.mu.Lock()
|
|
c.text.WriteString(e.Text)
|
|
c.mu.Unlock()
|
|
case KindToolStart:
|
|
e.Tool = capTool(e.Tool)
|
|
c.flushReasoning(ctx, turn)
|
|
c.flushText(ctx, turn)
|
|
case KindToolEnd:
|
|
e.Tool = capTool(e.Tool)
|
|
if e.Tool != nil {
|
|
if e.Tool.OK {
|
|
e.Tool.Card = c.takeCard(e.Tool.Name, e.Tool.Output)
|
|
}
|
|
e.Tool.Seq = c.appendEntry(ctx, Entry{Turn: turn, Role: RoleTool, Card: e.Tool.Card, Text: e.Tool.Name + ": " + e.Tool.Summary + "\n" + e.Tool.Output})
|
|
}
|
|
case KindError:
|
|
// An error event carries one of the fixed reasons, never the text
|
|
// of an internal error.
|
|
e.Text = fixedReason(e.Text)
|
|
// The structured cause is the chat's to set: a harness cannot.
|
|
e.Code, e.Model, e.Retry, e.Detail = "", "", 0, ""
|
|
e.Tool = nil
|
|
// Only the chat knows whether an error ended the turn; a harness
|
|
// cannot claim it.
|
|
e.Fatal = false
|
|
c.flushReasoning(ctx, turn)
|
|
case KindCompacted:
|
|
// Only the token counts travel; the transcript keeps every message.
|
|
e.Text, e.Tool = "", nil
|
|
case KindPaused:
|
|
// Only the step limit travels.
|
|
e.Text, e.Tool, e.Before, e.After = "", nil, 0, 0
|
|
c.flushReasoning(ctx, turn)
|
|
default:
|
|
return // turn_start, checkpoint and turn_end belong to the chat
|
|
}
|
|
c.emit(e)
|
|
}
|
|
|
|
// Limits of a tool event, as documented on ToolEvent.
|
|
const (
|
|
maxSummary = 200
|
|
maxOutput = 2048
|
|
)
|
|
|
|
// capTool returns a copy of t with the documented limits applied, so that no
|
|
// harness can put long text in an event.
|
|
func capTool(t *ToolEvent) *ToolEvent {
|
|
if t == nil {
|
|
return nil
|
|
}
|
|
cp := *t
|
|
cp.Card = nil // only a host tool sets a card, through the chat
|
|
cp.Seq = 0 // only the chat knows the entry of a call
|
|
cp.Name = CapText(cp.Name, maxSummary)
|
|
cp.Summary = CapText(cp.Summary, maxSummary)
|
|
cp.Output = CapText(cp.Output, maxOutput)
|
|
return &cp
|
|
}
|
|
|
|
// fixedReason returns text when it is one of the fixed reasons, or one of the
|
|
// reasons that reasonFor builds from an error without quoting it, and the
|
|
// generic reason otherwise.
|
|
func fixedReason(text string) string {
|
|
switch text {
|
|
case reasonAgent, reasonTranscript, reasonSave, reasonRefresh, reasonCheckpoint, ReasonNotAllowed, ReasonQuota:
|
|
return text
|
|
}
|
|
if strings.HasPrefix(text, reasonContextPrefix) || strings.HasPrefix(text, reasonModelFailedPrefix) || strings.HasPrefix(text, reasonUnknownToolPrefix) {
|
|
return text
|
|
}
|
|
return reasonAgent
|
|
}
|
|
|
|
// Marks the model client puts in the error of a refused request, so that the
|
|
// loop can tell the user why without showing the text of an internal error.
|
|
const (
|
|
MarkNotAllowed = "[studio:not-allowed]"
|
|
MarkQuota = "[studio:quota]"
|
|
)
|
|
|
|
const (
|
|
reasonContextPrefix = "The model's context window is too small"
|
|
reasonModelFailedPrefix = "The model failed"
|
|
reasonUnknownToolPrefix = "The model called a tool that is not available"
|
|
)
|
|
|
|
var (
|
|
numberRe = regexp.MustCompile(`\d{3,}`)
|
|
httpStatusRe = regexp.MustCompile(`HTTP (\d{3})`)
|
|
)
|
|
|
|
var toolNameRe = regexp.MustCompile(`selected tool ([A-Za-z0-9_.:-]{1,64}) not found`)
|
|
|
|
// unknownToolReason says that the model called a tool the chat does not offer.
|
|
// When two connectors offer one tool name, the second is offered under the
|
|
// connector's name, so the hint names that rule.
|
|
func unknownToolReason(msg string) string {
|
|
reason := reasonUnknownToolPrefix
|
|
if m := toolNameRe.FindStringSubmatch(msg); m != nil {
|
|
reason += " (" + m[1] + ")"
|
|
}
|
|
return reason + ". A tool that two connectors both offer is offered as <connector>__<tool>. Try again, or switch the extra connectors off."
|
|
}
|
|
|
|
// contextReason explains that the built-in tools and the conversation do not
|
|
// fit the model's context window, and by how much when the error says.
|
|
func contextReason(msg string) string {
|
|
reason := reasonContextPrefix + " for the built-in tools and this conversation."
|
|
nums := numberRe.FindAllString(msg, -1)
|
|
if len(nums) >= 2 {
|
|
hi, lo := 0, 0
|
|
for i, n := range nums {
|
|
v, err := strconv.Atoi(n)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if i == 0 || v > hi {
|
|
hi = v
|
|
}
|
|
if i == 0 || v < lo {
|
|
lo = v
|
|
}
|
|
}
|
|
if hi > lo {
|
|
reason = reasonContextPrefix + " for the built-in tools and this conversation: it is about " + strconv.Itoa(hi-lo) + " tokens short."
|
|
}
|
|
}
|
|
return reason + " Use a model with a larger context window, or switch some tools off."
|
|
}
|
|
|
|
// addReasoning buffers a reasoning delta. Answer text that is still buffered
|
|
// is stored first, so the entries keep the order of the events.
|
|
func (c *Chat) addReasoning(ctx context.Context, turn int, delta string) {
|
|
c.mu.Lock()
|
|
pending := c.text.Len() > 0
|
|
c.mu.Unlock()
|
|
if pending {
|
|
c.flushText(ctx, turn)
|
|
}
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if c.reason.Len() == 0 && !c.reasonCut {
|
|
c.reasonFirst = time.Now()
|
|
}
|
|
if c.reasonCut {
|
|
return
|
|
}
|
|
if room := MaxReasoningBytes - len(reasoningCut); c.reason.Len()+len(delta) > room {
|
|
c.reason.WriteString(CapText(delta, room-c.reason.Len()))
|
|
c.reasonCut = true
|
|
return
|
|
}
|
|
c.reason.WriteString(delta)
|
|
}
|
|
|
|
const reasoningCut = "…"
|
|
|
|
// flushReasoning stores the reasoning of the step, when there is any. A store
|
|
// error is logged and dropped: reasoning never fails a turn.
|
|
func (c *Chat) flushReasoning(ctx context.Context, turn int) {
|
|
c.mu.Lock()
|
|
t, cut, first := c.reason.String(), c.reasonCut, c.reasonFirst
|
|
c.reason.Reset()
|
|
c.reasonCut = false
|
|
c.mu.Unlock()
|
|
if strings.TrimSpace(t) == "" {
|
|
return
|
|
}
|
|
if cut {
|
|
t += reasoningCut
|
|
}
|
|
dur := max(time.Since(first), time.Millisecond)
|
|
e := Entry{Turn: turn, Role: RoleReasoning, Text: t, Dur: dur}
|
|
if _, err := c.m.o.Store.AppendEntry(ctx, c.id, e); err != nil {
|
|
c.m.log.Error("session: append reasoning entry", "chat", c.id, "error", err)
|
|
}
|
|
}
|
|
|
|
func (c *Chat) flushText(ctx context.Context, turn int) {
|
|
c.mu.Lock()
|
|
t := c.text.String()
|
|
c.text.Reset()
|
|
c.mu.Unlock()
|
|
if strings.TrimSpace(t) != "" {
|
|
c.appendEntry(ctx, Entry{Turn: turn, Role: RoleAssistant, Text: t})
|
|
}
|
|
}
|
|
|
|
// History returns the whole transcript.
|
|
func (c *Chat) History(ctx context.Context) ([]Entry, error) {
|
|
var all []Entry
|
|
var after int64
|
|
for {
|
|
page, err := c.m.o.Store.Entries(ctx, c.id, after, 500)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
all = append(all, page...)
|
|
if len(page) < 500 {
|
|
return all, nil
|
|
}
|
|
after = page[len(page)-1].Seq
|
|
}
|
|
}
|
|
|
|
// Send starts a turn, or injects the message into the running one. Uploads
|
|
// are stored in the chat folder before the turn starts; a message with files
|
|
// is refused with ErrTurnRunning while a turn runs.
|
|
func (c *Chat) Send(ctx context.Context, msg Message) error { return c.send(ctx, msg, false) }
|
|
|
|
// send is Send. logged is true when the message is in the transcript already.
|
|
func (c *Chat) send(ctx context.Context, msg Message, logged bool) error {
|
|
text := strings.TrimSpace(msg.Text)
|
|
if text == "" && msg.Note == "" && len(msg.Files) == 0 && len(msg.Attachments) == 0 && msg.Directive == "" {
|
|
return fmt.Errorf("%w: empty message", ErrInvalid)
|
|
}
|
|
entry := Entry{Role: RoleUser, Text: text, Note: msg.Note, Attachments: msg.Attachments, Loop: msg.Loop, Invoked: msg.Invoked}
|
|
if msg.Goal {
|
|
entry = Entry{Role: RoleGoal, Text: text, Note: GoalLineContinue, Rev: int64(msg.GoalTurn)}
|
|
}
|
|
for {
|
|
c.mu.Lock()
|
|
if c.closed {
|
|
c.mu.Unlock()
|
|
return ErrClosed
|
|
}
|
|
ch := c.renaming
|
|
if ch == nil {
|
|
break
|
|
}
|
|
c.mu.Unlock()
|
|
select {
|
|
case <-ch:
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
}
|
|
if c.running {
|
|
if c.stopped {
|
|
// Stop was called and the turn has not ended: a message would be
|
|
// queued and then dropped.
|
|
c.mu.Unlock()
|
|
return fmt.Errorf("%w: the turn is stopping", ErrTurnRunning)
|
|
}
|
|
hs, turn, swapping := c.hs, c.turn, c.swapping
|
|
if hs == nil || swapping {
|
|
// The harness is being swapped: queue the message for the next
|
|
// turn, which runs on the new harness.
|
|
c.mu.Unlock()
|
|
if len(msg.Files) > 0 {
|
|
return fmt.Errorf("%w: files can be sent when the turn has ended", ErrTurnRunning)
|
|
}
|
|
if !logged {
|
|
entry.Turn = turn
|
|
c.appendEntry(ctx, entry)
|
|
}
|
|
return c.queuePending(ctx, msg, withDirective(msg.Directive, c.modelText(entry)))
|
|
}
|
|
// Taken under mu, so a swap that starts later waits for this inject.
|
|
c.injectMu.RLock()
|
|
c.mu.Unlock()
|
|
if len(msg.Files) > 0 {
|
|
c.injectMu.RUnlock()
|
|
return fmt.Errorf("%w: files can be sent when the turn has ended", ErrTurnRunning)
|
|
}
|
|
if !logged {
|
|
entry.Turn = turn
|
|
c.appendEntry(ctx, entry)
|
|
}
|
|
err := hs.Inject(withDirective(msg.Directive, c.modelText(entry)))
|
|
c.injectMu.RUnlock()
|
|
if !errors.Is(err, ErrNoTurn) {
|
|
return err
|
|
}
|
|
// The turn is ending. Queue the message for the next one, or start
|
|
// it here when the turn has ended meanwhile.
|
|
c.mu.Lock()
|
|
if c.running {
|
|
if c.stopped {
|
|
c.mu.Unlock()
|
|
return fmt.Errorf("%w: the turn is stopping", ErrTurnRunning)
|
|
}
|
|
c.pending = append(c.pending, withDirective(msg.Directive, c.modelText(entry)))
|
|
c.mu.Unlock()
|
|
return nil
|
|
}
|
|
c.mu.Unlock()
|
|
return c.send(ctx, msg, true)
|
|
}
|
|
// Reserve the turn, then store the files without the lock.
|
|
c.running, c.stopped = true, false
|
|
c.done = make(chan struct{})
|
|
done := c.done
|
|
c.mu.Unlock()
|
|
|
|
saved, err := c.saveUploads(ctx, msg.Files)
|
|
if err != nil {
|
|
c.mu.Lock()
|
|
c.endLoopLocked(done)
|
|
c.mu.Unlock()
|
|
return err
|
|
}
|
|
if len(saved) > 0 {
|
|
c.emit(Event{Kind: KindFiles})
|
|
}
|
|
// The transcript keeps the words and the files apart; the model gets
|
|
// them together, as it always has.
|
|
entry.Attachments = append(slices.Clip(entry.Attachments), saved...)
|
|
full := withDirective(msg.Directive, c.modelText(entry))
|
|
if !logged {
|
|
entry.Turn = c.turnNow() + 1
|
|
c.appendEntry(ctx, entry)
|
|
}
|
|
c.m.wg.Add(1)
|
|
go c.loop(full, len(saved) > 0, msg.Media, done)
|
|
return nil
|
|
}
|
|
|
|
// queuePending queues text for the next turn of the running loop, or starts
|
|
// it when the turn has ended meanwhile. The message is in the transcript.
|
|
func (c *Chat) queuePending(ctx context.Context, msg Message, text string) error {
|
|
c.mu.Lock()
|
|
if c.running {
|
|
if c.stopped {
|
|
c.mu.Unlock()
|
|
return fmt.Errorf("%w: the turn is stopping", ErrTurnRunning)
|
|
}
|
|
c.pending = append(c.pending, text)
|
|
c.mu.Unlock()
|
|
return nil
|
|
}
|
|
c.mu.Unlock()
|
|
return c.send(ctx, msg, true)
|
|
}
|
|
|
|
// Attach stores files in the chat folder and returns them as attachments of
|
|
// a message that the caller sends. It works while a turn runs: the files are
|
|
// in the workspace at once, and the model reads them by path when the message
|
|
// reaches it.
|
|
func (c *Chat) Attach(ctx context.Context, files []Upload) ([]Attachment, error) {
|
|
saved, err := c.saveUploads(ctx, files)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(saved) > 0 {
|
|
c.emit(Event{Kind: KindFiles})
|
|
}
|
|
return saved, nil
|
|
}
|
|
|
|
func (c *Chat) turnNow() int {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
return c.turn
|
|
}
|
|
|
|
// endLoopLocked ends the running state. The caller holds c.mu.
|
|
func (c *Chat) endLoopLocked(done chan struct{}) {
|
|
c.running, c.cancel, c.pending = false, nil, nil
|
|
close(done)
|
|
}
|
|
|
|
// loop runs the turn, then the messages that arrived while it was ending.
|
|
// The chat leaves the running state before turn_end is emitted, so a consumer
|
|
// that sees turn_end can call SetTitle or Send at once. endMu keeps the next
|
|
// turn_start behind that turn_end.
|
|
func (c *Chat) loop(text string, refresh bool, media []Media, done chan struct{}) {
|
|
defer c.m.wg.Done()
|
|
for {
|
|
n := c.runTurn(text, refresh, media)
|
|
media = nil
|
|
c.mu.Lock()
|
|
more := len(c.pending) > 0 && !c.closed && !c.stopped
|
|
if more {
|
|
text, c.pending, refresh = strings.Join(c.pending, "\n\n"), nil, false
|
|
} else {
|
|
c.endLoopLocked(done)
|
|
}
|
|
c.endMu.Lock()
|
|
c.mu.Unlock()
|
|
c.emit(Event{Kind: KindTurnEnd, Turn: n})
|
|
c.endMu.Unlock()
|
|
c.touch()
|
|
if !more {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// runTurn runs one turn up to and including its checkpoint event, and returns
|
|
// the turn number. The loop emits turn_end.
|
|
func (c *Chat) runTurn(text string, refresh bool, media []Media) int {
|
|
c.mu.Lock()
|
|
c.turn++
|
|
n := c.turn
|
|
ctx, cancel := context.WithCancel(c.m.ctx)
|
|
c.cancel, c.turnCtx = cancel, ctx
|
|
hs := c.hs
|
|
skip := c.stopped
|
|
c.mu.Unlock()
|
|
c.clearCards()
|
|
defer func() {
|
|
cancel()
|
|
c.clearCards()
|
|
c.mu.Lock()
|
|
c.turnCtx = nil
|
|
c.mu.Unlock()
|
|
}()
|
|
|
|
c.endMu.Lock()
|
|
c.emit(Event{Kind: KindTurnStart, Turn: n})
|
|
c.endMu.Unlock()
|
|
note := ""
|
|
if !skip {
|
|
var hookRefresh bool
|
|
note, hookRefresh = c.applyChatTools(ctx)
|
|
c.mu.Lock()
|
|
hs = c.hs // a changed set of tools restarted the harness
|
|
c.mu.Unlock()
|
|
// The files that the prompt block names changed. Make the sandbox see
|
|
// them, as it sees an upload.
|
|
refresh = refresh || hookRefresh
|
|
}
|
|
if refresh && !skip && ctx.Err() == nil {
|
|
if err := c.refresh(ctx); err != nil {
|
|
c.m.log.Warn("session: refresh before the turn", "chat", c.id, "error", err)
|
|
c.emit(Event{Kind: KindError, Turn: n, Text: reasonRefresh})
|
|
}
|
|
}
|
|
if !skip && hs != nil {
|
|
toModel := text
|
|
if note != "" {
|
|
// The note is for the model only: the transcript keeps the user's words.
|
|
toModel = "(System note: " + note + ")\n\n" + text
|
|
}
|
|
err := safeSend(ctx, hs, toModel, media, c.m.log)
|
|
c.mu.Lock()
|
|
stopped := c.stopped
|
|
c.mu.Unlock()
|
|
if err != nil && !(stopped && (errors.Is(err, context.Canceled) || ctx.Err() != nil)) {
|
|
c.m.log.Error("session: the harness failed", "chat", c.id, "turn", n, "error", err)
|
|
f := Classify(err)
|
|
c.emit(Event{Kind: KindError, Turn: n, Text: f.Reason, Code: f.Code, Model: f.Model, Retry: f.RetryAfter, Detail: f.Detail, Fatal: true})
|
|
}
|
|
}
|
|
c.flushReasoning(context.Background(), n)
|
|
c.flushText(context.Background(), n)
|
|
|
|
ch := c.checkpoint(n, text)
|
|
c.appendEntry(context.Background(), Entry{Turn: n, Role: RoleCheckpoint, Rev: ch.Rev, Text: strings.Join(ch.Paths, "\n")})
|
|
// The turn count advances with every turn, so that a restart never
|
|
// numbers a turn twice. The state stays the old one when Export fails.
|
|
c.mu.Lock()
|
|
c.rec.Turns = n
|
|
c.mu.Unlock()
|
|
if hs != nil {
|
|
if state, err := hs.Export(); err != nil {
|
|
c.m.log.Error("session: export the harness state", "chat", c.id, "error", err)
|
|
} else {
|
|
c.mu.Lock()
|
|
c.rec.HarnessState = state
|
|
c.stateSeq++
|
|
c.mu.Unlock()
|
|
}
|
|
}
|
|
if err := c.persist(context.Background()); err != nil {
|
|
c.emit(Event{Kind: KindError, Turn: n, Text: reasonSave})
|
|
}
|
|
c.emit(Event{Kind: KindCheckpoint, Turn: n, Change: &ch})
|
|
if ch.Rev != 0 {
|
|
c.emit(Event{Kind: KindFiles, Turn: n})
|
|
}
|
|
return n
|
|
}
|
|
|
|
// checkpoint commits the turn's changes, when the chat has a live sandbox.
|
|
func (c *Chat) checkpoint(n int, text string) ChangeEvent {
|
|
c.vmMu.Lock()
|
|
defer c.vmMu.Unlock()
|
|
if c.vm.sb == nil {
|
|
return ChangeEvent{}
|
|
}
|
|
title := fmt.Sprintf("Turn %d: %s", n, CapText(strings.SplitN(text, "\n", 2)[0], 60))
|
|
ctx, cancel := context.WithTimeout(context.Background(), checkpointLimit)
|
|
defer cancel()
|
|
sweepTemp(ctx, c.vm.sb)
|
|
cs, conflicts, err := c.vm.sb.Checkpoint(ctx, title)
|
|
if err != nil {
|
|
c.m.log.Error("session: checkpoint", "chat", c.id, "turn", n, "error", err)
|
|
return ChangeEvent{Err: reasonCheckpoint}
|
|
}
|
|
seen := map[string]bool{}
|
|
var paths []string
|
|
for _, op := range cs.Ops {
|
|
for _, p := range []string{op.NewPath, op.OldPath} {
|
|
if p != "" && !seen[p] && len(paths) < maxPaths {
|
|
seen[p] = true
|
|
paths = append(paths, p)
|
|
}
|
|
}
|
|
}
|
|
return ChangeEvent{Rev: cs.Rev, Paths: paths, Conflicts: conflicts}
|
|
}
|
|
|
|
// Stop interrupts the running turn and waits until it has ended. The turn
|
|
// still checkpoints, so partial work is kept and can be undone. Messages that
|
|
// are queued for the next turn are dropped.
|
|
func (c *Chat) Stop(ctx context.Context) error {
|
|
c.mu.Lock()
|
|
if !c.running {
|
|
c.mu.Unlock()
|
|
return nil
|
|
}
|
|
c.stopped, c.pending = true, nil
|
|
cancel, done, hs := c.cancel, c.done, c.hs
|
|
c.mu.Unlock()
|
|
if cancel != nil {
|
|
cancel()
|
|
}
|
|
if hs != nil {
|
|
_ = hs.Interrupt()
|
|
}
|
|
select {
|
|
case <-done:
|
|
return nil
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
}
|
|
|
|
// Close stops the turn, closes the harness and the event channel. The chat
|
|
// stays stored; its sandbox follows the idle rule. Open with the same ID
|
|
// opens it again.
|
|
func (c *Chat) Close() error { return c.close(context.Background()) }
|
|
|
|
// close is Close. ctx bounds the wait for the running turn.
|
|
func (c *Chat) close(ctx context.Context) error {
|
|
// Mark the chat closed first, so that no Send starts a turn while Close
|
|
// waits for the running one.
|
|
c.mu.Lock()
|
|
if c.closed {
|
|
c.mu.Unlock()
|
|
return nil
|
|
}
|
|
c.closed = true
|
|
c.mu.Unlock()
|
|
sctx, cancel := context.WithTimeout(ctx, checkpointLimit+time.Minute)
|
|
defer cancel()
|
|
stopErr := c.Stop(sctx)
|
|
c.mu.Lock()
|
|
hs := c.hs
|
|
c.hs = nil
|
|
c.mu.Unlock()
|
|
var err error
|
|
if hs != nil {
|
|
err = hs.Close()
|
|
}
|
|
c.evMu.RLock()
|
|
b := c.bus
|
|
c.evMu.RUnlock()
|
|
b.close()
|
|
c.releaseMemory(ctx)
|
|
return errors.Join(stopErr, err)
|
|
}
|
|
|
|
// saveUploads stores the files in the chat folder and returns them as
|
|
// attachments.
|
|
func (c *Chat) saveUploads(ctx context.Context, files []Upload) ([]Attachment, error) {
|
|
if len(files) == 0 {
|
|
return nil, nil
|
|
}
|
|
if c.m.o.Workspace == nil {
|
|
return nil, ErrNoWorkspace
|
|
}
|
|
folder, err := c.ensureFolder(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
actor, user, _ := c.access()
|
|
home := HomePath(actor.Principal)
|
|
var out []Attachment
|
|
for _, f := range files {
|
|
if f.Body == nil {
|
|
return nil, fmt.Errorf("%w: file %q has no body", ErrInvalid, f.Name)
|
|
}
|
|
name := path.Base(strings.ReplaceAll(f.Name, "\\", "/"))
|
|
if name == "." || name == "/" || name == ".." {
|
|
name = "file"
|
|
}
|
|
n, err := c.m.o.Workspace.Put(ctx, user, ChatsPath(actor.Principal)+"/"+folder+"/"+name, f.Body, workspace.PutOptions{})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("session: store %q: %w", name, err)
|
|
}
|
|
out = append(out, Attachment{
|
|
Path: strings.TrimPrefix(n.Path, home), Name: n.Name, Size: n.Size, Mime: MimeOf(n.Name), Version: n.Version,
|
|
})
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// ensureFolder creates the chat folder on first use and returns its name. A
|
|
// chat whose folder name was taken for its work folder (reserveFolder) gets
|
|
// the folder under that name.
|
|
func (c *Chat) ensureFolder(ctx context.Context) (string, error) {
|
|
name, err := c.reserveFolder(ctx)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
actor, user, _ := c.access()
|
|
dir := ChatsPath(actor.Principal) + "/" + name
|
|
c.m.layoutMu.Lock()
|
|
defer c.m.layoutMu.Unlock()
|
|
if err := mkdirOnce(ctx, c.m.o.Workspace, user, dir); err != nil {
|
|
return "", err
|
|
}
|
|
return name, nil
|
|
}
|
|
|
|
// reserveFolder gives the chat the name of its folder, without making the
|
|
// folder, and returns it: the work folder that the prompt names lives in it,
|
|
// and is made when something is saved there. A name that a folder or another
|
|
// recent chat of the user has is taken.
|
|
func (c *Chat) reserveFolder(ctx context.Context) (string, error) {
|
|
c.m.layoutMu.Lock()
|
|
defer c.m.layoutMu.Unlock()
|
|
c.mu.Lock()
|
|
rec := c.rec
|
|
c.mu.Unlock()
|
|
if rec.Folder != "" {
|
|
return rec.Folder, nil
|
|
}
|
|
taken, err := c.folderTaken(ctx, "")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
name, err := uniqueName(FolderName(rec.Created, rec.Title), taken)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
c.mu.Lock()
|
|
c.rec.Folder = name
|
|
c.mu.Unlock()
|
|
// The folder name stays in memory when the save fails; the save at the end
|
|
// of the turn stores it.
|
|
_ = c.persist(ctx)
|
|
return name, nil
|
|
}
|
|
|
|
// maxFolderPeers is how many recent chats of the user a new folder name is
|
|
// checked against. A chat takes its name at its first turn, so a chat that
|
|
// could have the same name (same day, same title) is a recent one.
|
|
const maxFolderPeers = 200
|
|
|
|
// folderTaken returns the check of uniqueName for a chat folder name: a
|
|
// folder of that name exists, or another recent chat of the user holds the
|
|
// name for a folder it has not made yet. keep is a name that is free anyway
|
|
// (the chat's own name, on a rename).
|
|
func (c *Chat) folderTaken(ctx context.Context, keep string) (func(string) (bool, error), error) {
|
|
actor, user, _ := c.access()
|
|
chats := ChatsPath(actor.Principal)
|
|
peers, err := c.m.o.Store.ListChats(ctx, actor.Principal, ChatCursor{}, maxFolderPeers)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
held := map[string]bool{}
|
|
for _, p := range peers {
|
|
if p.ID != c.id && p.Folder != "" {
|
|
held[workspace.FoldName(p.Folder)] = true
|
|
}
|
|
}
|
|
return func(n string) (bool, error) {
|
|
if n == keep {
|
|
return false, nil
|
|
}
|
|
if held[workspace.FoldName(n)] {
|
|
return true, nil
|
|
}
|
|
_, err := c.m.o.Workspace.Stat(ctx, user, chats+"/"+n)
|
|
if errors.Is(err, workspace.ErrNotFound) {
|
|
return false, nil
|
|
}
|
|
return err == nil, err
|
|
}, nil
|
|
}
|
|
|
|
// mkdirOnce makes the folder dir and its parents when dir is missing. A
|
|
// folder that is there is left as it is, so a second call changes nothing.
|
|
func mkdirOnce(ctx context.Context, ws workspace.Store, a workspace.Actor, dir string) error {
|
|
n, err := ws.Stat(ctx, a, dir)
|
|
switch {
|
|
case err == nil && n.Kind == workspace.KindDir:
|
|
return nil
|
|
case err == nil:
|
|
return fmt.Errorf("%w: %s is not a folder", workspace.ErrExists, dir)
|
|
case !errors.Is(err, workspace.ErrNotFound):
|
|
return err
|
|
}
|
|
if _, err := ws.Mkdir(ctx, a, dir); err != nil && !errors.Is(err, workspace.ErrExists) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// EnsureWorkFolder makes the work folder of a chat (workfiles.Folder) of
|
|
// principal when it is missing, as the user a: a tool calls it before the
|
|
// chat saves its first working file. It does nothing for a chat with no
|
|
// folder name, and nothing the second time.
|
|
func EnsureWorkFolder(ctx context.Context, ws workspace.Store, a workspace.Actor, principal, chatFolder string) error {
|
|
if ws == nil || chatFolder == "" || !validPrincipal(principal) {
|
|
return nil
|
|
}
|
|
return mkdirOnce(ctx, ws, a, HomePath(principal)+workfiles.Folder(chatFolder))
|
|
}
|
|
|
|
// workFolderBlock names the work folder of the chat for the prompt. It is ""
|
|
// when the chat has no files, or its folder cannot be named this turn, or it
|
|
// has no folder name and reserve is false.
|
|
func (c *Chat) workFolderBlock(ctx context.Context, reserve bool) string {
|
|
if c.m.o.Workspace == nil {
|
|
return ""
|
|
}
|
|
if !reserve {
|
|
c.mu.Lock()
|
|
name := c.rec.Folder
|
|
c.mu.Unlock()
|
|
if name == "" {
|
|
return ""
|
|
}
|
|
return c.workPrompt(name)
|
|
}
|
|
name, err := c.reserveFolder(ctx)
|
|
if err != nil {
|
|
c.m.log.Warn("session: no work folder this turn", "chat", c.id, "error", err)
|
|
return ""
|
|
}
|
|
return c.workPrompt(name)
|
|
}
|
|
|
|
// workPrompt names the work folder by the chat's view: in a scoped chat the
|
|
// chat folder is its own mount, at /workspace/chat.
|
|
func (c *Chat) workPrompt(name string) string {
|
|
_, _, view := c.access()
|
|
if p := NewPlace(view); p.Scoped() {
|
|
return workfiles.ScopedPrompt(p.PrimaryWritable())
|
|
}
|
|
return workfiles.Prompt(workfiles.GuestFolder(name))
|
|
}
|
|
|
|
// SetTitle renames the chat and, when the chat folder exists, the folder. It
|
|
// returns ErrTurnRunning while a turn runs. When the chat has a sandbox, the
|
|
// sandbox is refreshed so that it sees the new folder name: its processes end.
|
|
func (c *Chat) SetTitle(ctx context.Context, title string) error {
|
|
title = CleanTitle(title)
|
|
if title == "" {
|
|
return fmt.Errorf("%w: empty title", ErrInvalid)
|
|
}
|
|
c.mu.Lock()
|
|
switch {
|
|
case c.closed:
|
|
c.mu.Unlock()
|
|
return ErrClosed
|
|
case c.running || c.renaming != nil:
|
|
c.mu.Unlock()
|
|
return ErrTurnRunning
|
|
}
|
|
c.renaming = make(chan struct{})
|
|
ch := c.renaming
|
|
c.mu.Unlock()
|
|
defer func() {
|
|
c.mu.Lock()
|
|
c.renaming = nil
|
|
c.mu.Unlock()
|
|
close(ch)
|
|
}()
|
|
|
|
c.mu.Lock()
|
|
old, created := c.rec.Folder, c.rec.Created
|
|
c.mu.Unlock()
|
|
if base := FolderName(created, title); old != "" && !strings.EqualFold(base, old) {
|
|
if err := c.renameFolder(ctx, old, base); err != nil {
|
|
return err
|
|
}
|
|
c.emit(Event{Kind: KindFiles})
|
|
}
|
|
c.mu.Lock()
|
|
c.rec.Title = title
|
|
c.mu.Unlock()
|
|
return c.persist(ctx)
|
|
}
|
|
|
|
// renameFolder moves the chat folder old to a free name that starts with
|
|
// base. It commits what the sandbox wrote under the old name first, and
|
|
// refreshes the sandbox afterwards so that it sees the new name.
|
|
func (c *Chat) renameFolder(ctx context.Context, old, base string) error {
|
|
if c.m.o.Workspace == nil {
|
|
return nil
|
|
}
|
|
sb, release, err := c.acquire(ctx, false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if sb != nil {
|
|
defer release()
|
|
sweepTemp(ctx, sb)
|
|
if _, _, err := sb.Checkpoint(ctx, "Rename chat folder"); err != nil {
|
|
return fmt.Errorf("session: save the sandbox before the rename: %w", err)
|
|
}
|
|
}
|
|
actor, user, _ := c.access()
|
|
chats := ChatsPath(actor.Principal)
|
|
c.m.layoutMu.Lock()
|
|
taken, err := c.folderTaken(ctx, old)
|
|
var name string
|
|
if err == nil {
|
|
name, err = uniqueName(base, taken)
|
|
}
|
|
if err == nil && name != old {
|
|
_, err = c.m.o.Workspace.Move(ctx, user, chats+"/"+old, chats+"/"+name)
|
|
// A name kept for a work folder that was never made moves by itself.
|
|
if errors.Is(err, workspace.ErrNotFound) {
|
|
err = nil
|
|
}
|
|
}
|
|
c.m.layoutMu.Unlock()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c.mu.Lock()
|
|
c.rec.Folder = name
|
|
c.mu.Unlock()
|
|
if sb != nil {
|
|
if err := sb.Refresh(ctx); err != nil {
|
|
c.m.log.Warn("session: refresh after the rename", "chat", c.id, "error", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// sweepTemp removes the temporary files that an interrupted write left in the
|
|
// guest, so that no checkpoint commits one. Its errors are ignored: the
|
|
// checkpoint still runs.
|
|
func sweepTemp(ctx context.Context, sb sandbox.Sandbox) {
|
|
sctx, cancel := context.WithTimeout(ctx, time.Minute)
|
|
defer cancel()
|
|
p, err := sb.Exec(sctx, sandbox.Cmd{Args: []string{"find", ".", "-name", tempPrefix + "*", "-type", "f", "-delete"}, Dir: GuestRoot})
|
|
if err == nil {
|
|
_, _ = p.Wait()
|
|
}
|
|
}
|
|
|
|
// stopTimer stops the idle timer, if one is armed.
|
|
func (c *Chat) stopTimer() {
|
|
c.tmu.Lock()
|
|
defer c.tmu.Unlock()
|
|
if c.timer != nil {
|
|
c.timer.Stop()
|
|
c.timer = nil
|
|
}
|
|
}
|
|
|
|
// safeSend runs hs.Send and turns a panic into an error, so that a bug in a
|
|
// harness ends one turn and not the process.
|
|
func safeSend(ctx context.Context, hs HarnessSession, text string, media []Media, log *slog.Logger) (err error) {
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
log.Error("session: the harness panicked", "panic", fmt.Sprint(r), "stack", string(debug.Stack()))
|
|
err = errors.New("the harness panicked")
|
|
}
|
|
}()
|
|
if ms, ok := hs.(MediaSession); ok && len(media) > 0 {
|
|
return ms.SendMedia(ctx, text, media)
|
|
}
|
|
return hs.Send(ctx, text)
|
|
}
|
|
|
|
// guardTools makes a panic in a tool an error result, so that the harness
|
|
// goes on and the process lives.
|
|
func (c *Chat) guardTools(tools []Tool) []Tool {
|
|
log := c.m.log
|
|
out := make([]Tool, len(tools))
|
|
for i, tool := range tools {
|
|
run := tool.Run
|
|
name := tool.Name
|
|
tool.Run = func(ctx context.Context, args json.RawMessage) (res string, err error) {
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
log.Error("session: a tool panicked", "tool", name, "panic", fmt.Sprint(r), "stack", string(debug.Stack()))
|
|
c.emit(Event{Kind: KindError, Text: reasonAgent})
|
|
res, err = "", errors.New("the tool failed")
|
|
}
|
|
}()
|
|
// Whatever context the harness passes, Stop must end the tool:
|
|
// bind it to the context of the turn.
|
|
c.mu.Lock()
|
|
tctx := c.turnCtx
|
|
c.mu.Unlock()
|
|
if tctx == nil {
|
|
tctx = c.m.ctx
|
|
}
|
|
rctx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
defer context.AfterFunc(tctx, cancel)()
|
|
return run(rctx, args)
|
|
}
|
|
out[i] = tool
|
|
}
|
|
return out
|
|
}
|
|
|
|
// releaseMemory drops what a closed chat does not need: the harness state (it is in
|
|
// the store) and the event bus. A stuck bus would otherwise keep its 512-slot
|
|
// channel for as long as the manager lives. The state stays in memory when it
|
|
// cannot be saved.
|
|
func (c *Chat) releaseMemory(ctx context.Context) {
|
|
c.mu.Lock()
|
|
dirty := c.stateSeq != c.savedSeq
|
|
c.mu.Unlock()
|
|
if dirty && c.persist(ctx) != nil {
|
|
return
|
|
}
|
|
c.mu.Lock()
|
|
c.rec.HarnessState, c.released = nil, true
|
|
c.mu.Unlock()
|
|
c.evMu.Lock()
|
|
c.bus = closedBus()
|
|
c.evMu.Unlock()
|
|
}
|