fix(bridge): rawRPC direct polling + SDK analysis docs + trial-and-error log
- Root cause: getDiagnostics.lastStepIndex is stale, SDK EventMonitor cannot detect real-time step changes
- Fix: Direct rawRPC('GetCascadeTrajectorySteps') polling every 5s
- Relay: PLANNER_RESPONSE, NOTIFY_USER, TASK_BOUNDARY, WAITING steps
- Added: docs/discord-bridge-analysis.md (full SDK architecture analysis)
- Added: docs/devlog/entries/20260308-003.md (trial-and-error history)
- Added: antigravity-sdk-main/ source reference
- Vikunja: #252 done, #253 created, #251 commented
This commit is contained in:
2
antigravity-sdk-main/.github/FUNDING.yml
vendored
Normal file
2
antigravity-sdk-main/.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
custom:
|
||||
- https://github.com/Kanezal/antigravity-sdk#support
|
||||
49
antigravity-sdk-main/.github/workflows/docs.yml
vendored
Normal file
49
antigravity-sdk-main/.github/workflows/docs.yml
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
name: Deploy TypeDoc to GitHub Pages
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'src/**'
|
||||
- 'package.json'
|
||||
- 'tsconfig.json'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- run: npx typedoc --out docs-site src/index.ts --tsconfig tsconfig.json
|
||||
|
||||
- uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
path: docs-site
|
||||
|
||||
deploy:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
steps:
|
||||
- id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
15
antigravity-sdk-main/.gitignore
vendored
Normal file
15
antigravity-sdk-main/.gitignore
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
node_modules/
|
||||
dist/
|
||||
docs-site/
|
||||
*.tsbuildinfo
|
||||
.DS_Store
|
||||
|
||||
# Internal reference — not for public repo
|
||||
GEMINI.md
|
||||
docs/implementation-plan.md
|
||||
docs/internals.md
|
||||
scripts/
|
||||
|
||||
# Extensions (separate repo)
|
||||
example-extension/
|
||||
xray-extension/
|
||||
68
antigravity-sdk-main/LEGAL.md
Normal file
68
antigravity-sdk-main/LEGAL.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# Legal Notice
|
||||
|
||||
## Disclaimer
|
||||
|
||||
This project is an unofficial, community-maintained SDK for building extensions
|
||||
for [Antigravity IDE](https://antigravity.dev). It is **not affiliated with,
|
||||
endorsed by, or sponsored by Google LLC or any of its subsidiaries.**
|
||||
|
||||
## Nature of the Project
|
||||
|
||||
Antigravity SDK provides a **TypeScript library** for VS Code extension
|
||||
developers who want to build tools that work within Antigravity IDE.
|
||||
|
||||
The SDK interacts with Antigravity exclusively through:
|
||||
|
||||
- **VS Code Extension API** — the standard, documented `vscode.*` namespace
|
||||
that all extensions use
|
||||
- **Registered commands** — commands exposed by Antigravity through the
|
||||
standard `vscode.commands` interface
|
||||
- **Local state files** — reading (not writing) locally stored settings
|
||||
|
||||
## Compliance
|
||||
|
||||
- This SDK **does not access** Google's backend servers, gRPC endpoints,
|
||||
or authentication systems directly.
|
||||
- This SDK **does not extract** AI models, training data, weights, or
|
||||
proprietary algorithms.
|
||||
- This SDK **does not bypass** security features, licensing, rate limits,
|
||||
or usage restrictions.
|
||||
- This SDK **does not proxy** or relay requests to Google's infrastructure.
|
||||
- All communication goes through Antigravity's own extension host — the same
|
||||
mechanism used by any VS Code extension.
|
||||
|
||||
## Interoperability
|
||||
|
||||
This SDK is developed to enable interoperability between Antigravity IDE
|
||||
and third-party extensions, as provided by:
|
||||
|
||||
- **EU Software Directive** (Directive 2009/24/EC), Article 6 — permits
|
||||
analysis of software for the purpose of achieving interoperability
|
||||
- **UK Copyright, Designs and Patents Act 1988**, Section 50B
|
||||
- Similar provisions in other jurisdictions
|
||||
|
||||
The API interfaces documented in this project were derived through observation
|
||||
of Antigravity's public extension API surface — the same surface available to
|
||||
any VS Code extension running inside Antigravity.
|
||||
|
||||
## User Responsibility
|
||||
|
||||
Users and extension developers are responsible for ensuring their use of
|
||||
this SDK and any extensions built with it comply with applicable terms of
|
||||
service and local laws.
|
||||
|
||||
Extension developers should:
|
||||
|
||||
1. Not use the SDK to access Google's backend directly
|
||||
2. Not use the SDK to extract or replicate AI model behavior
|
||||
3. Not use the SDK to bypass security or licensing restrictions
|
||||
4. Follow Antigravity's extension guidelines where applicable
|
||||
|
||||
## Takedown
|
||||
|
||||
If Google or the Antigravity team requests removal of this project, we will
|
||||
comply promptly. Contact: [open a GitHub issue](https://github.com/Kanezal/antigravity-sdk/issues).
|
||||
|
||||
## License
|
||||
|
||||
This project is released under the [GNU Affero General Public License v3.0](LICENSE).
|
||||
644
antigravity-sdk-main/LICENSE
Normal file
644
antigravity-sdk-main/LICENSE
Normal file
@@ -0,0 +1,644 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they receive
|
||||
widespread use, become available for other developers to incorporate.
|
||||
Many developers of free software are heartened and encouraged by the
|
||||
resulting cooperation. However, in the case of software used on network
|
||||
servers, this result may fail to come about. The GNU General Public
|
||||
License permits making a modified version and letting the public access
|
||||
it on a server without ever releasing its source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding Source
|
||||
of the work are being offered to the general public at no charge under
|
||||
subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied by
|
||||
the Installation Information. But this requirement does not apply if
|
||||
neither you nor any third party retains the ability to install modified
|
||||
object code on the User Product (for example, the work has been
|
||||
installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in source
|
||||
code form), and must require no special password or key for unpacking,
|
||||
reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions; the
|
||||
above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE
|
||||
OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
|
||||
DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR
|
||||
A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH
|
||||
HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
Antigravity SDK
|
||||
Copyright (C) 2026 Kanezal
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
348
antigravity-sdk-main/README.md
Normal file
348
antigravity-sdk-main/README.md
Normal file
@@ -0,0 +1,348 @@
|
||||
<div align="center">
|
||||
|
||||
# Antigravity SDK
|
||||
|
||||
**Community SDK for building extensions for [Antigravity IDE](https://antigravity.dev)**
|
||||
|
||||
[](https://www.npmjs.com/package/antigravity-sdk)
|
||||
[](LICENSE)
|
||||
[](https://github.com/Kanezal/antigravity-sdk#support)
|
||||
|
||||
*Build powerful extensions that work alongside Antigravity's AI agent.*
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## What is this?
|
||||
|
||||
A TypeScript SDK for building **VS Code extensions** that extend Antigravity IDE. It gives you programmatic access to the agent's conversations, preferences, step control, real-time activity monitoring, and a declarative API for integrating custom UI directly into the Agent View — all through Antigravity's own extension protocols.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> This SDK is designed **exclusively** for building Antigravity extensions. It is **not** a tool for integrating Antigravity with third-party applications, extracting data, or proxying requests. See [Compliance](#compliance).
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
npm install antigravity-sdk
|
||||
```
|
||||
|
||||
```typescript
|
||||
import { AntigravitySDK } from 'antigravity-sdk';
|
||||
|
||||
export async function activate(context: vscode.ExtensionContext) {
|
||||
const sdk = new AntigravitySDK(context);
|
||||
await sdk.initialize();
|
||||
|
||||
// List conversations with real titles
|
||||
const sessions = await sdk.cascade.getSessions();
|
||||
console.log(`${sessions.length} conversations`);
|
||||
|
||||
// Read all 16 agent preferences
|
||||
const prefs = await sdk.cascade.getPreferences();
|
||||
console.log('Terminal policy:', prefs.terminalExecutionPolicy);
|
||||
|
||||
// Monitor agent activity in real time
|
||||
sdk.monitor.onStepCountChanged((e) => {
|
||||
console.log(`${e.title}: +${e.delta} steps`);
|
||||
});
|
||||
sdk.monitor.onActiveSessionChanged((e) => {
|
||||
console.log(`Switched to: ${e.title}`);
|
||||
});
|
||||
sdk.monitor.start();
|
||||
|
||||
// Accept/reject agent steps programmatically
|
||||
await sdk.cascade.acceptStep();
|
||||
await sdk.cascade.acceptTerminalCommand();
|
||||
|
||||
context.subscriptions.push(sdk);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
### Agent View UI Integration
|
||||
|
||||
The SDK provides **9 integration points** in the Agent View panel — add buttons, metadata, badges, menu items, and interactive elements with a fluent, declarative API. Everything is theme-aware and survives Antigravity updates via auto-repair.
|
||||
|
||||
```typescript
|
||||
import { IntegrationManager, IntegrationPoint } from 'antigravity-sdk';
|
||||
|
||||
const ui = new IntegrationManager();
|
||||
|
||||
// Fluent API — chain calls
|
||||
ui.addTopBarButton('stats', '📊', 'Show Stats', {
|
||||
title: 'Session Stats',
|
||||
rows: [{ key: 'Steps:', value: '42' }],
|
||||
})
|
||||
.addInputButton('tokens', '🔢', 'Token Counter')
|
||||
.addTurnMetadata('meta', ['turnNumber', 'userCharCount', 'aiCharCount', 'codeBlocks'])
|
||||
.addUserBadges('badges', 'charCount')
|
||||
.addBotAction('inspect', '🔍', 'Inspect Response')
|
||||
.addDropdownItem('export', 'Export Chat', '📋')
|
||||
.addTitleInteraction('title', 'dblclick', 'Double-click to bookmark');
|
||||
|
||||
await ui.install();
|
||||
ui.enableAutoRepair(); // Survives Antigravity updates
|
||||
```
|
||||
|
||||
| Integration Point | Location | Use Cases |
|
||||
|-------------------|----------|-----------|
|
||||
| `TOP_BAR` | Header icon bar | Session overview, navigation |
|
||||
| `TOP_RIGHT` | Before close button | Status indicators, quick toggle |
|
||||
| `INPUT_AREA` | Next to send button | Token counter, prompt templates |
|
||||
| `BOTTOM_ICONS` | Bottom icon row | Mode switches, quick actions |
|
||||
| `TURN_METADATA` | Inside each turn | Character count, code block stats, turn numbers |
|
||||
| `USER_BADGE` | User message bubble | Message length indicator |
|
||||
| `BOT_ACTION` | Next to Good/Bad | Response analysis, copy actions |
|
||||
| `DROPDOWN_MENU` | 3-dot overflow menu | Export, settings, debug tools |
|
||||
| `CHAT_TITLE` | Conversation title | Rename, bookmark on interaction |
|
||||
|
||||
> [!NOTE]
|
||||
> The integration script runs in the renderer process, independent of the extension. The SDK uses a **heartbeat mechanism** to prevent orphaned integrations: `sdk.initialize()` refreshes a timestamp marker, and the script silently exits if the marker is stale (48h). Disabling your extension will automatically stop the integration on the next IDE restart after the grace period.
|
||||
|
||||
### Conversation Management
|
||||
|
||||
Full control over Cascade conversations — list, create, switch, send messages, and manage agent steps.
|
||||
|
||||
```typescript
|
||||
// List sessions with titles, step counts, timestamps
|
||||
const sessions = await sdk.cascade.getSessions();
|
||||
|
||||
// Switch to a conversation
|
||||
await sdk.cascade.focusSession(sessions[0].id);
|
||||
|
||||
// Send a message to the active chat
|
||||
await sdk.cascade.sendPrompt('Analyze this file');
|
||||
|
||||
// Create a background conversation
|
||||
const id = await sdk.cascade.createBackgroundSession('Run tests quietly');
|
||||
```
|
||||
|
||||
### Real-Time Event Monitoring
|
||||
|
||||
Watch for state changes as they happen — new conversations, step progress, session switches, preference updates.
|
||||
|
||||
```typescript
|
||||
// Agent made progress (added steps)
|
||||
sdk.monitor.onStepCountChanged((e) => {
|
||||
statusBar.text = `${e.title}: step ${e.newCount}`;
|
||||
});
|
||||
|
||||
// User switched to a different conversation
|
||||
sdk.monitor.onActiveSessionChanged((e) => {
|
||||
console.log(`Now viewing: ${e.title}`);
|
||||
});
|
||||
|
||||
// New conversation created
|
||||
sdk.monitor.onNewConversation(() => {
|
||||
console.log('New conversation detected');
|
||||
});
|
||||
|
||||
// Any USS state changed (preferences, settings, etc.)
|
||||
sdk.monitor.onStateChanged((e) => {
|
||||
console.log(`${e.key}: ${e.previousSize} → ${e.newSize} bytes`);
|
||||
});
|
||||
|
||||
sdk.monitor.start(3000, 5000); // USS poll: 3s, trajectory poll: 5s
|
||||
```
|
||||
|
||||
### Agent Step Control
|
||||
|
||||
Programmatically accept, reject, or run agent actions — build approval workflows, auto-accept policies, or custom review UIs.
|
||||
|
||||
```typescript
|
||||
await sdk.cascade.acceptStep(); // Accept code edit
|
||||
await sdk.cascade.rejectStep(); // Reject code edit
|
||||
await sdk.cascade.acceptTerminalCommand(); // Accept terminal command
|
||||
await sdk.cascade.rejectTerminalCommand(); // Reject terminal command
|
||||
await sdk.cascade.runTerminalCommand(); // Run pending command
|
||||
await sdk.cascade.acceptCommand(); // Accept non-terminal action
|
||||
```
|
||||
|
||||
### State & Preferences
|
||||
|
||||
Read the agent's current settings — terminal policies, secure mode, sandbox config, and more. Decoded directly from protobuf sentinel values.
|
||||
|
||||
```typescript
|
||||
const prefs = await sdk.cascade.getPreferences();
|
||||
|
||||
prefs.terminalExecutionPolicy // OFF | AUTO | EAGER
|
||||
prefs.artifactReviewPolicy // ALWAYS | TURBO | AUTO
|
||||
prefs.secureModeEnabled // boolean
|
||||
prefs.terminalSandboxEnabled // boolean
|
||||
prefs.shellIntegrationEnabled // boolean
|
||||
prefs.allowNonWorkspaceFiles // boolean
|
||||
// ... 16 preferences total
|
||||
```
|
||||
|
||||
### IDE Diagnostics
|
||||
|
||||
Access system information, extension logs, and recent conversation metadata.
|
||||
|
||||
```typescript
|
||||
const diag = await sdk.cascade.getDiagnostics();
|
||||
|
||||
console.log(diag.systemInfo.operatingSystem);
|
||||
console.log(diag.systemInfo.userName);
|
||||
console.log(diag.isRemote); // SSH?
|
||||
|
||||
// MCP URL, browser port, git status
|
||||
const mcpUrl = await sdk.cascade.getMcpUrl();
|
||||
const browserPort = await sdk.cascade.getBrowserPort();
|
||||
const ignored = await sdk.cascade.isFileGitIgnored('secret.env');
|
||||
```
|
||||
|
||||
### Headless Cascade (LSBridge)
|
||||
|
||||
Create and manage conversations programmatically through the Language Server — no UI flicker, no panel switching.
|
||||
|
||||
```typescript
|
||||
import { Models } from 'antigravity-sdk';
|
||||
|
||||
// Create a headless cascade with model selection
|
||||
const cascadeId = await sdk.ls.createCascade({
|
||||
text: 'Analyze test coverage in this project',
|
||||
model: Models.GEMINI_FLASH,
|
||||
});
|
||||
|
||||
// Send follow-up messages
|
||||
await sdk.ls.sendMessage({
|
||||
cascadeId,
|
||||
text: 'Now fix the failing tests',
|
||||
model: Models.GEMINI_PRO_HIGH,
|
||||
});
|
||||
|
||||
// Focus in UI when ready
|
||||
await sdk.ls.focusCascade(cascadeId);
|
||||
|
||||
// Or make raw RPC calls to any of the 68 verified LS methods
|
||||
const status = await sdk.ls.getUserStatus();
|
||||
const cascades = await sdk.ls.listCascades();
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> LSBridge auto-discovers the Language Server port and CSRF token from the running LS process. If auto-discovery fails (sandboxed environments), use `sdk.ls.setConnection(port, csrfToken)` manually.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Your Extension
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────────────────┐
|
||||
│ antigravity-sdk │
|
||||
│ │
|
||||
│ sdk.cascade ← CascadeManager │
|
||||
│ Sessions, preferences, step control │
|
||||
│ │
|
||||
│ sdk.monitor ← EventMonitor │
|
||||
│ USS polling, trajectory tracking │
|
||||
│ │
|
||||
│ sdk.integration ← IntegrationManager │
|
||||
│ Declarative UI for Agent View │
|
||||
│ │
|
||||
│ sdk.commands ← CommandBridge │
|
||||
│ 60+ verified Antigravity commands │
|
||||
│ │
|
||||
│ sdk.state ← StateBridge │
|
||||
│ Read-only access to USS preferences │
|
||||
│ │
|
||||
│ sdk.ls ← LSBridge │
|
||||
│ Local LS communication (advanced) │
|
||||
│ │
|
||||
└────────────────────────────────────────-─┘
|
||||
│
|
||||
vscode.commands.executeCommand()
|
||||
+ read-only state.vscdb (sql.js)
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> The SDK uses `sql.js` (pure JS/WASM SQLite) instead of `better-sqlite3` because Antigravity's Electron ABI (v140 / Node v22.21.1) is incompatible with native modules. This was verified in runtime.
|
||||
|
||||
---
|
||||
|
||||
## Compliance
|
||||
|
||||
> [!CAUTION]
|
||||
> **Token extraction is a violation of Google's Terms of Service.**
|
||||
>
|
||||
> The SDK **actively blocks** access to authentication tokens (`oauthToken`, `agentManagerInitState`, and other sensitive keys). Any attempt to read these keys will throw an error.
|
||||
>
|
||||
> Extracting, storing, forwarding, or reusing Antigravity OAuth tokens — directly or through third-party tools — violates Google's TOS and may result in account termination.
|
||||
|
||||
### What this SDK is for
|
||||
|
||||
- Building **VS Code extensions** that run inside Antigravity IDE
|
||||
- Extending Antigravity's functionality for your own workflows
|
||||
- Adding custom UI elements to the Agent View
|
||||
- Monitoring and automating agent step approval
|
||||
- Reading preferences and conversation metadata
|
||||
|
||||
### What this SDK is NOT for
|
||||
|
||||
- Integrating Antigravity with external applications or services
|
||||
- Proxying or relaying requests to Google's infrastructure
|
||||
- Extracting AI model outputs for training other models
|
||||
- Accessing Google's backend servers, gRPC endpoints, or auth systems
|
||||
- Building alternative clients or wrappers around Antigravity
|
||||
|
||||
### How it works
|
||||
|
||||
All SDK communication goes through three safe, local channels:
|
||||
|
||||
1. **`vscode.commands.executeCommand()`** — the standard VS Code Extension API that all extensions use. Antigravity decides what to execute.
|
||||
2. **Read-only local state** — the SDK reads `state.vscdb` for preferences and metadata, never writes.
|
||||
3. **Local Language Server** — the SDK communicates with the LS process on `127.0.0.1` using the same ConnectRPC protocol that Antigravity itself uses. Authentication is via an ephemeral per-session CSRF token (not the user's OAuth token). No data leaves the local machine through this channel.
|
||||
|
||||
The SDK includes a `SENSITIVE_KEYS` blocklist that prevents extension developers from accidentally (or intentionally) accessing authentication data.
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
- **[GEMINI.md](GEMINI.md)** — Full internal architecture docs, verified DOM selectors, protobuf schemas
|
||||
- **[LEGAL.md](LEGAL.md)** — Legal notice, interoperability rights, compliance details
|
||||
- **[API Reference](https://kanezal.github.io/antigravity-sdk)** — TypeDoc (coming soon)
|
||||
|
||||
---
|
||||
|
||||
## Contributing
|
||||
|
||||
This is a community project. PRs welcome!
|
||||
|
||||
1. Fork the repo
|
||||
2. Create a feature branch
|
||||
3. Follow the existing code style
|
||||
4. Add JSDoc comments for all public methods
|
||||
5. Submit a PR
|
||||
|
||||
---
|
||||
|
||||
## Disclaimer
|
||||
|
||||
> [!WARNING]
|
||||
> This project is not affiliated with Google or the Antigravity team. The SDK interacts with Antigravity through its existing extension API and local state files. Use at your own risk and in compliance with applicable terms of service.
|
||||
|
||||
---
|
||||
|
||||
## ❤️ Support
|
||||
|
||||
If you find this project useful and want to support its development, you can send **USDT** to:
|
||||
|
||||
| Network | Address |
|
||||
|---------|---------|
|
||||
| **TON** | `UQCjVh3C3mZc44GjT2IDsS4pmeOoUgRNxWMcb85NS5Bz_v1d` |
|
||||
| **TRON (TRC20)** | `TH3JKGjNrSDCsjkkSuneaSMZoJYF7CNTXD` |
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
[AGPL-3.0-or-later](LICENSE)
|
||||
3106
antigravity-sdk-main/package-lock.json
generated
Normal file
3106
antigravity-sdk-main/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
52
antigravity-sdk-main/package.json
Normal file
52
antigravity-sdk-main/package.json
Normal file
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "antigravity-sdk",
|
||||
"version": "1.6.0",
|
||||
"description": "Community SDK for building extensions for Antigravity IDE",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"dev": "tsup --watch",
|
||||
"lint": "eslint src/",
|
||||
"docs": "typedoc --out docs-site src/index.ts",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"keywords": [
|
||||
"antigravity",
|
||||
"antigravity-ide",
|
||||
"google-antigravity",
|
||||
"sdk",
|
||||
"cascade",
|
||||
"ai-agent",
|
||||
"vscode-extension"
|
||||
],
|
||||
"author": "Kanezal",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Kanezal/antigravity-sdk.git"
|
||||
},
|
||||
"homepage": "https://kanezal.github.io/antigravity-sdk",
|
||||
"engines": {
|
||||
"node": ">=16.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/vscode": "^1.85.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.0.0",
|
||||
"@types/vscode": "^1.85.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.0.0",
|
||||
"@typescript-eslint/parser": "^8.0.0",
|
||||
"eslint": "^9.0.0",
|
||||
"tsup": "^8.0.0",
|
||||
"typedoc": "^0.27.0",
|
||||
"typescript": "^5.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"sql.js": "^1.14.0"
|
||||
}
|
||||
}
|
||||
527
antigravity-sdk-main/src/cascade/cascade-manager.ts
Normal file
527
antigravity-sdk-main/src/cascade/cascade-manager.ts
Normal file
@@ -0,0 +1,527 @@
|
||||
/**
|
||||
* Cascade Manager — Session listing, creation, and monitoring.
|
||||
*
|
||||
* Provides high-level API to interact with Cascade conversations
|
||||
* using verified transport layer (CommandBridge + StateBridge).
|
||||
*
|
||||
* VERIFIED 2026-02-28: getDiagnostics.recentTrajectories returns clean JSON
|
||||
* with { googleAgentId, trajectoryId, summary, lastStepIndex, lastModifiedTime }.
|
||||
*
|
||||
* @module cascade/cascade-manager
|
||||
*/
|
||||
|
||||
import { IDisposable, DisposableStore } from '../core/disposable';
|
||||
import { EventEmitter, Event } from '../core/events';
|
||||
import { Logger } from '../core/logger';
|
||||
import type {
|
||||
ITrajectoryEntry,
|
||||
IAgentPreferences,
|
||||
IDiagnosticsInfo,
|
||||
ICreateSessionOptions,
|
||||
} from '../core/types';
|
||||
import { CommandBridge, AntigravityCommands } from '../transport/command-bridge';
|
||||
import { StateBridge } from '../transport/state-bridge';
|
||||
|
||||
const log = new Logger('CascadeManager');
|
||||
|
||||
/**
|
||||
* Manages Cascade conversations.
|
||||
*
|
||||
* Primary data source: `antigravity.getDiagnostics` → `recentTrajectories`
|
||||
* Fallback: `antigravityUnifiedStateSync.trajectorySummaries` protobuf parsing
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const manager = new CascadeManager(commands, state);
|
||||
* await manager.initialize();
|
||||
*
|
||||
* // List sessions (real titles from getDiagnostics)
|
||||
* const sessions = await manager.getSessions();
|
||||
* sessions.forEach(s => console.log(`${s.title} (step ${s.stepCount})`));
|
||||
*
|
||||
* // Read preferences (all 16 sentinel values)
|
||||
* const prefs = await manager.getPreferences();
|
||||
*
|
||||
* // Create & send
|
||||
* await manager.createSession({ task: 'Analyze coverage', background: true });
|
||||
* ```
|
||||
*/
|
||||
export class CascadeManager implements IDisposable {
|
||||
private readonly _disposables = new DisposableStore();
|
||||
private _sessions: ITrajectoryEntry[] = [];
|
||||
private _initialized = false;
|
||||
|
||||
// Events
|
||||
private readonly _onSessionsChanged = this._disposables.add(new EventEmitter<ITrajectoryEntry[]>());
|
||||
/** Fires when the session list changes */
|
||||
public readonly onSessionsChanged: Event<ITrajectoryEntry[]> = this._onSessionsChanged.event;
|
||||
|
||||
constructor(
|
||||
private readonly _commands: CommandBridge,
|
||||
private readonly _state: StateBridge,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Initialize the cascade manager.
|
||||
* Loads the initial session list from getDiagnostics.
|
||||
*/
|
||||
async initialize(): Promise<void> {
|
||||
if (this._initialized) return;
|
||||
|
||||
await this._loadSessions();
|
||||
this._initialized = true;
|
||||
log.info(`Initialized with ${this._sessions.length} sessions`);
|
||||
}
|
||||
|
||||
// ─── Read API ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Get all known Cascade sessions.
|
||||
*
|
||||
* Uses `getDiagnostics.recentTrajectories` (clean JSON with titles).
|
||||
*
|
||||
* @returns List of trajectory entries sorted by recency
|
||||
*/
|
||||
async getSessions(): Promise<ITrajectoryEntry[]> {
|
||||
if (!this._initialized) {
|
||||
await this._loadSessions();
|
||||
}
|
||||
return [...this._sessions];
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the session list.
|
||||
*
|
||||
* @returns Updated session list
|
||||
*/
|
||||
async refreshSessions(): Promise<ITrajectoryEntry[]> {
|
||||
await this._loadSessions();
|
||||
this._onSessionsChanged.fire(this._sessions);
|
||||
return [...this._sessions];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get agent preferences (all 16 sentinel values).
|
||||
*/
|
||||
async getPreferences(): Promise<IAgentPreferences> {
|
||||
return this._state.getAgentPreferences();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get IDE diagnostics (176KB JSON with system info, logs, trajectories).
|
||||
*
|
||||
* Structure (verified):
|
||||
* - isRemote, systemInfo (OS, user, email)
|
||||
* - extensionLogs (Array[375])
|
||||
* - rendererLogs, mainThreadLogs, agentWindowConsoleLogs
|
||||
* - languageServerLogs
|
||||
* - recentTrajectories (Array[10])
|
||||
*
|
||||
* @returns Parsed diagnostics information
|
||||
*/
|
||||
async getDiagnostics(): Promise<IDiagnosticsInfo> {
|
||||
const raw = await this._commands.execute<string>(AntigravityCommands.GET_DIAGNOSTICS);
|
||||
|
||||
if (!raw || typeof raw !== 'string') {
|
||||
throw new Error('getDiagnostics returned unexpected type');
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(raw);
|
||||
|
||||
return {
|
||||
isRemote: parsed.isRemote ?? false,
|
||||
systemInfo: {
|
||||
operatingSystem: parsed.systemInfo?.operatingSystem ?? 'unknown',
|
||||
timestamp: parsed.systemInfo?.timestamp ?? '',
|
||||
userEmail: parsed.systemInfo?.userEmail ?? '',
|
||||
userName: parsed.systemInfo?.userName ?? '',
|
||||
},
|
||||
raw: parsed,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Chrome DevTools MCP URL.
|
||||
*
|
||||
* Verified: returns `http://127.0.0.1:{port}/mcp`
|
||||
*
|
||||
* @returns MCP URL string
|
||||
*/
|
||||
async getMcpUrl(): Promise<string> {
|
||||
const result = await this._commands.execute<string>('antigravity.getChromeDevtoolsMcpUrl');
|
||||
return result ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file is gitignored.
|
||||
*
|
||||
* @param filePath - Relative or absolute file path
|
||||
* @returns true if gitignored, false/null otherwise
|
||||
*/
|
||||
async isFileGitIgnored(filePath: string): Promise<boolean> {
|
||||
const result = await this._commands.execute<boolean | null>('antigravity.isFileGitIgnored', filePath);
|
||||
return result === true;
|
||||
}
|
||||
|
||||
// ─── Write API ──────────────────────────────────────────────────────────
|
||||
//
|
||||
// Two-layer architecture (VERIFIED 2026-02-28):
|
||||
//
|
||||
// Layer 1 -- HEADLESS LS API (RECOMMENDED):
|
||||
// Access: sdk.ls (LSBridge from antigravity-sdk)
|
||||
// Method: Preact VNode tree -> component.props.lsClient -> 148 LS methods
|
||||
// Creates cascade WITHOUT opening panel or switching UI.
|
||||
// Usage: await sdk.ls.createCascade({ text: 'prompt' })
|
||||
//
|
||||
// Layer 2 — COMMAND API (FALLBACK, this file):
|
||||
// Access: vscode.commands.executeCommand (extension host)
|
||||
// Method: startNewConversation → sendPromptToAgentPanel → restore
|
||||
// PROBLEM: Always switches UI, causes flickering, race conditions.
|
||||
// Use only when renderer integration is not available.
|
||||
//
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Create a new Cascade conversation via VS Code commands.
|
||||
*
|
||||
* ⚠️ **FALLBACK APPROACH** — causes UI flickering.
|
||||
* For true headless creation, use `sdk.ls.createCascade()`
|
||||
* from the SDK's LS bridge (see LSBridge module).
|
||||
*
|
||||
* VERIFIED 2026-02-28:
|
||||
* - `startNewConversation` ✅ creates new chat (but switches UI)
|
||||
* - `prioritized.chat.openNewConversation` ❌ does NOT create new
|
||||
* - `sendPromptToAgentPanel` ✅ sends to currently visible chat (always opens panel)
|
||||
* - `sendTextToChat` ❌ does not visibly work
|
||||
*
|
||||
* @param options - Session creation options
|
||||
* @returns Session ID (googleAgentId) or empty string if not detected
|
||||
*/
|
||||
async createSession(options: ICreateSessionOptions): Promise<string> {
|
||||
log.info(`Creating session (command fallback): "${options.task.substring(0, 50)}..."`);
|
||||
|
||||
// Snapshot current sessions to detect the new one
|
||||
const beforeIds = new Set(this._sessions.map(s => s.id));
|
||||
|
||||
// Remember current active session (for background restore)
|
||||
let previousActiveId = '';
|
||||
if (options.background) {
|
||||
try {
|
||||
const raw = await this._commands.execute<string>(AntigravityCommands.GET_DIAGNOSTICS);
|
||||
if (raw && typeof raw === 'string') {
|
||||
const diag = JSON.parse(raw);
|
||||
if (Array.isArray(diag.recentTrajectories) && diag.recentTrajectories.length > 0) {
|
||||
previousActiveId = diag.recentTrajectories[0].googleAgentId ?? '';
|
||||
}
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
|
||||
// Create new conversation (VERIFIED: startNewConversation works)
|
||||
await this._commands.execute(AntigravityCommands.START_NEW_CONVERSATION);
|
||||
await this._delay(1500); // Wait for UI to initialize
|
||||
|
||||
// Send initial prompt
|
||||
if (options.task) {
|
||||
await this._commands.execute(AntigravityCommands.SEND_PROMPT_TO_AGENT, options.task);
|
||||
}
|
||||
|
||||
// Mark as background if requested
|
||||
if (options.background) {
|
||||
await this._commands.execute(AntigravityCommands.TRACK_BACKGROUND_CONVERSATION);
|
||||
}
|
||||
|
||||
// Wait for new session to appear in getDiagnostics
|
||||
const newId = await this._waitForNewSession(beforeIds, 8000);
|
||||
|
||||
// If background: switch back to original conversation
|
||||
if (options.background && previousActiveId) {
|
||||
await this._delay(500);
|
||||
await this._commands.execute(AntigravityCommands.SET_VISIBLE_CONVERSATION, previousActiveId);
|
||||
log.info(`Background session created, restored to ${previousActiveId}`);
|
||||
}
|
||||
|
||||
if (newId) {
|
||||
log.info(`Session created: ${newId}`);
|
||||
} else {
|
||||
log.warn('Session created but ID not detected within timeout');
|
||||
}
|
||||
|
||||
return newId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a background Cascade conversation via commands.
|
||||
*
|
||||
* ⚠️ **FALLBACK** — Uses quick-switch approach (UI flickers briefly).
|
||||
* For true headless background sessions, use the SDK's LS bridge:
|
||||
* ```typescript
|
||||
* // Using LSBridge:
|
||||
* const cascadeId = await sdk.ls.createCascade({ text: 'task', modelId: 1018 });
|
||||
* ```
|
||||
*
|
||||
* @param task - Initial task/prompt to send
|
||||
* @returns Session ID or empty string
|
||||
*/
|
||||
async createBackgroundSession(task: string): Promise<string> {
|
||||
return this.createSession({ task, background: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message to the active Cascade conversation.
|
||||
*
|
||||
* Uses `antigravity.sendTextToChat` — the primary text sending command.
|
||||
*/
|
||||
async sendMessage(text: string): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.SEND_TEXT_TO_CHAT, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a prompt directly to the agent panel.
|
||||
*
|
||||
* Uses `antigravity.sendPromptToAgentPanel` — focuses the agent panel.
|
||||
*/
|
||||
async sendPrompt(text: string): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.SEND_PROMPT_TO_AGENT, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a chat action message (e.g., typing indicator, feedback).
|
||||
*
|
||||
* Uses `antigravity.sendChatActionMessage`.
|
||||
*/
|
||||
async sendChatAction(action: string): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.SEND_CHAT_ACTION, action);
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch to a specific conversation.
|
||||
*
|
||||
* @param sessionId - Conversation UUID (googleAgentId)
|
||||
*/
|
||||
async focusSession(sessionId: string): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.SET_VISIBLE_CONVERSATION, sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a new conversation in the agent panel (prioritized command).
|
||||
*
|
||||
* Uses `antigravity.prioritized.chat.openNewConversation` which both
|
||||
* opens the panel AND creates a fresh conversation.
|
||||
*/
|
||||
async openNewConversation(): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.OPEN_NEW_CONVERSATION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a Cascade action.
|
||||
*
|
||||
* Uses `antigravity.executeCascadeAction`.
|
||||
*
|
||||
* @param action - Action data to execute
|
||||
*/
|
||||
async executeCascadeAction(action: unknown): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.EXECUTE_CASCADE_ACTION, action);
|
||||
}
|
||||
|
||||
// ─── Step Control ───────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Accept the current agent step (code edit, file write, etc.).
|
||||
*
|
||||
* Uses `antigravity.agent.acceptAgentStep`.
|
||||
*/
|
||||
async acceptStep(): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.ACCEPT_AGENT_STEP);
|
||||
}
|
||||
|
||||
/** Reject the current agent step. */
|
||||
async rejectStep(): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.REJECT_AGENT_STEP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept a pending command (non-terminal, e.g. file edit confirmation).
|
||||
*
|
||||
* Uses `antigravity.command.accept`.
|
||||
* This is DIFFERENT from terminalCommand.accept.
|
||||
*/
|
||||
async acceptCommand(): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.COMMAND_ACCEPT);
|
||||
}
|
||||
|
||||
/** Reject a pending command (non-terminal). */
|
||||
async rejectCommand(): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.COMMAND_REJECT);
|
||||
}
|
||||
|
||||
// ─── Terminal Control ───────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Accept a pending terminal command.
|
||||
*
|
||||
* Uses `antigravity.terminalCommand.accept`.
|
||||
*/
|
||||
async acceptTerminalCommand(): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.TERMINAL_ACCEPT);
|
||||
}
|
||||
|
||||
/** Reject a pending terminal command. */
|
||||
async rejectTerminalCommand(): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.TERMINAL_REJECT);
|
||||
}
|
||||
|
||||
/** Run a pending terminal command. */
|
||||
async runTerminalCommand(): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.TERMINAL_RUN);
|
||||
}
|
||||
|
||||
// ─── Panel Control ──────────────────────────────────────────────────────
|
||||
|
||||
/** Open the Cascade agent panel */
|
||||
async openPanel(): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.OPEN_AGENT_PANEL);
|
||||
}
|
||||
|
||||
/** Focus the Cascade agent panel */
|
||||
async focusPanel(): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.FOCUS_AGENT_PANEL);
|
||||
}
|
||||
|
||||
/** Open the agent side panel */
|
||||
async openSidePanel(): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.OPEN_AGENT_SIDE_PANEL);
|
||||
}
|
||||
|
||||
/** Focus the agent side panel */
|
||||
async focusSidePanel(): Promise<void> {
|
||||
await this._commands.execute(AntigravityCommands.FOCUS_AGENT_SIDE_PANEL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the browser integration port (e.g., 57401).
|
||||
*/
|
||||
async getBrowserPort(): Promise<number> {
|
||||
return this._commands.execute<number>(AntigravityCommands.GET_BROWSER_PORT);
|
||||
}
|
||||
|
||||
// ─── Private ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Load sessions from getDiagnostics.recentTrajectories (clean JSON).
|
||||
*
|
||||
* VERIFIED structure per entry:
|
||||
* {
|
||||
* googleAgentId: "uuid", ← conversation ID
|
||||
* trajectoryId: "uuid", ← internal trajectory ID
|
||||
* summary: "title", ← human-readable title
|
||||
* lastStepIndex: 992, ← step count
|
||||
* lastModifiedTime: "ISO" ← last activity
|
||||
* }
|
||||
*/
|
||||
private async _loadSessions(): Promise<void> {
|
||||
try {
|
||||
// Primary: getDiagnostics.recentTrajectories (10 most recent, with titles)
|
||||
const raw = await this._commands.execute<string>(AntigravityCommands.GET_DIAGNOSTICS);
|
||||
if (raw && typeof raw === 'string') {
|
||||
const diag = JSON.parse(raw);
|
||||
if (Array.isArray(diag.recentTrajectories)) {
|
||||
this._sessions = diag.recentTrajectories.map((entry: any) => ({
|
||||
id: entry.googleAgentId ?? '',
|
||||
title: entry.summary ?? 'Untitled',
|
||||
stepCount: entry.lastStepIndex ?? 0,
|
||||
workspaceUri: '',
|
||||
lastModifiedTime: entry.lastModifiedTime ?? '',
|
||||
trajectoryId: entry.trajectoryId ?? '',
|
||||
}));
|
||||
log.debug(`Loaded ${this._sessions.length} sessions from getDiagnostics`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
log.warn('getDiagnostics failed, falling back to USS', error);
|
||||
}
|
||||
|
||||
// Fallback: parse trajectory summaries protobuf
|
||||
try {
|
||||
await this._loadSessionsFromUSS();
|
||||
} catch (error) {
|
||||
log.error('Failed to load sessions from USS', error);
|
||||
this._sessions = [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback: extract sessions from USS trajectory summaries protobuf.
|
||||
*/
|
||||
private async _loadSessionsFromUSS(): Promise<void> {
|
||||
const raw = await this._state.getRawValue('antigravityUnifiedStateSync.trajectorySummaries');
|
||||
if (!raw) {
|
||||
this._sessions = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const buffer = Buffer.from(raw, 'base64');
|
||||
const text = buffer.toString('utf8');
|
||||
|
||||
// Extract UUIDs
|
||||
const uuids = [...new Set(text.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g) || [])];
|
||||
|
||||
this._sessions = uuids.map((id, i) => ({
|
||||
id,
|
||||
title: `Conversation ${i + 1}`,
|
||||
stepCount: 0,
|
||||
workspaceUri: '',
|
||||
}));
|
||||
|
||||
log.debug(`Loaded ${this._sessions.length} sessions from USS (fallback)`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a new session to appear in getDiagnostics.
|
||||
* Polls every 500ms up to timeoutMs.
|
||||
*
|
||||
* @returns New session ID or empty string if timeout
|
||||
*/
|
||||
private async _waitForNewSession(beforeIds: Set<string>, timeoutMs: number): Promise<string> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const pollInterval = 500;
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
await this._delay(pollInterval);
|
||||
|
||||
try {
|
||||
const raw = await this._commands.execute<string>(AntigravityCommands.GET_DIAGNOSTICS);
|
||||
if (!raw || typeof raw !== 'string') continue;
|
||||
|
||||
const diag = JSON.parse(raw);
|
||||
if (!Array.isArray(diag.recentTrajectories)) continue;
|
||||
|
||||
for (const entry of diag.recentTrajectories) {
|
||||
const id = entry.googleAgentId;
|
||||
if (id && !beforeIds.has(id)) {
|
||||
// Update local session list
|
||||
await this._loadSessions();
|
||||
return id;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore, retry
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple delay utility.
|
||||
*/
|
||||
private _delay(ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this._disposables.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
6
antigravity-sdk-main/src/cascade/index.ts
Normal file
6
antigravity-sdk-main/src/cascade/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* Cascade module re-exports.
|
||||
* @module cascade
|
||||
*/
|
||||
|
||||
export { CascadeManager } from './cascade-manager';
|
||||
73
antigravity-sdk-main/src/core/disposable.ts
Normal file
73
antigravity-sdk-main/src/core/disposable.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Disposable pattern for resource cleanup.
|
||||
*
|
||||
* @module disposable
|
||||
*/
|
||||
|
||||
/**
|
||||
* An object that can release resources when no longer needed.
|
||||
*/
|
||||
export interface IDisposable {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects multiple disposables and disposes them all at once.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const store = new DisposableStore();
|
||||
* store.add(someEventSub);
|
||||
* store.add(anotherSub);
|
||||
* // Later:
|
||||
* store.dispose(); // cleans up everything
|
||||
* ```
|
||||
*/
|
||||
export class DisposableStore implements IDisposable {
|
||||
private readonly _disposables: IDisposable[] = [];
|
||||
private _disposed = false;
|
||||
|
||||
/**
|
||||
* Add a disposable to the store.
|
||||
*
|
||||
* @param disposable - The disposable to track
|
||||
* @returns The same disposable (for chaining)
|
||||
*/
|
||||
add<T extends IDisposable>(disposable: T): T {
|
||||
if (this._disposed) {
|
||||
disposable.dispose();
|
||||
console.warn('[AntigravitySDK] Adding disposable to already disposed store');
|
||||
} else {
|
||||
this._disposables.push(disposable);
|
||||
}
|
||||
return disposable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispose all tracked disposables.
|
||||
*/
|
||||
dispose(): void {
|
||||
if (this._disposed) {
|
||||
return;
|
||||
}
|
||||
this._disposed = true;
|
||||
|
||||
for (const d of this._disposables) {
|
||||
try {
|
||||
d.dispose();
|
||||
} catch (error) {
|
||||
console.error('[AntigravitySDK] Dispose error:', error);
|
||||
}
|
||||
}
|
||||
this._disposables.length = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a disposable from a cleanup function.
|
||||
*
|
||||
* @param fn - Cleanup function to call on dispose
|
||||
*/
|
||||
export function toDisposable(fn: () => void): IDisposable {
|
||||
return { dispose: fn };
|
||||
}
|
||||
61
antigravity-sdk-main/src/core/errors.ts
Normal file
61
antigravity-sdk-main/src/core/errors.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* SDK-specific error classes.
|
||||
*
|
||||
* @module errors
|
||||
*/
|
||||
|
||||
/**
|
||||
* Base error for all Antigravity SDK errors.
|
||||
*/
|
||||
export class AntigravitySDKError extends Error {
|
||||
constructor(message: string) {
|
||||
super(`[AntigravitySDK] ${message}`);
|
||||
this.name = 'AntigravitySDKError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when Antigravity IDE is not detected or not running.
|
||||
*/
|
||||
export class AntigravityNotFoundError extends AntigravitySDKError {
|
||||
constructor() {
|
||||
super('Antigravity IDE not detected. Make sure this extension is running inside Antigravity.');
|
||||
this.name = 'AntigravityNotFoundError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when a command fails to execute.
|
||||
*/
|
||||
export class CommandExecutionError extends AntigravitySDKError {
|
||||
constructor(
|
||||
public readonly command: string,
|
||||
public readonly reason: string,
|
||||
) {
|
||||
super(`Command "${command}" failed: ${reason}`);
|
||||
this.name = 'CommandExecutionError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when the state database cannot be read.
|
||||
*/
|
||||
export class StateReadError extends AntigravitySDKError {
|
||||
constructor(
|
||||
public readonly key: string,
|
||||
public readonly reason: string,
|
||||
) {
|
||||
super(`Failed to read state key "${key}": ${reason}`);
|
||||
this.name = 'StateReadError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when a session/conversation is not found.
|
||||
*/
|
||||
export class SessionNotFoundError extends AntigravitySDKError {
|
||||
constructor(public readonly sessionId: string) {
|
||||
super(`Session "${sessionId}" not found`);
|
||||
this.name = 'SessionNotFoundError';
|
||||
}
|
||||
}
|
||||
99
antigravity-sdk-main/src/core/events.ts
Normal file
99
antigravity-sdk-main/src/core/events.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* Lightweight event system for SDK.
|
||||
*
|
||||
* Follows VS Code's `Event<T>` / `EventEmitter<T>` pattern.
|
||||
* Supports subscription, disposal, and one-shot listeners.
|
||||
*
|
||||
* @module events
|
||||
*/
|
||||
|
||||
import type { IDisposable } from './disposable';
|
||||
|
||||
/**
|
||||
* A function that represents a subscription to an event.
|
||||
* Call the returned disposable to unsubscribe.
|
||||
*/
|
||||
export type Event<T> = (listener: (e: T) => void) => IDisposable;
|
||||
|
||||
/**
|
||||
* Emits events to registered listeners.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const emitter = new EventEmitter<string>();
|
||||
*
|
||||
* const sub = emitter.event((msg) => console.log(msg));
|
||||
* emitter.fire('hello'); // logs: hello
|
||||
* sub.dispose();
|
||||
* emitter.fire('world'); // nothing happens
|
||||
* ```
|
||||
*/
|
||||
export class EventEmitter<T> implements IDisposable {
|
||||
private _listeners: Set<(e: T) => void> = new Set();
|
||||
private _disposed = false;
|
||||
|
||||
/**
|
||||
* The event that listeners can subscribe to.
|
||||
*/
|
||||
readonly event: Event<T> = (listener: (e: T) => void): IDisposable => {
|
||||
if (this._disposed) {
|
||||
throw new Error('EventEmitter has been disposed');
|
||||
}
|
||||
|
||||
this._listeners.add(listener);
|
||||
|
||||
return {
|
||||
dispose: () => {
|
||||
this._listeners.delete(listener);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Fire the event, notifying all listeners.
|
||||
*
|
||||
* @param data - The event data to send to listeners
|
||||
*/
|
||||
fire(data: T): void {
|
||||
if (this._disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const listener of this._listeners) {
|
||||
try {
|
||||
listener(data);
|
||||
} catch (error) {
|
||||
console.error('[AntigravitySDK] Event listener error:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to the event, but only fire once.
|
||||
*
|
||||
* @param listener - Callback to invoke once
|
||||
* @returns Disposable to cancel before the event fires
|
||||
*/
|
||||
once(listener: (e: T) => void): IDisposable {
|
||||
const sub = this.event((data) => {
|
||||
sub.dispose();
|
||||
listener(data);
|
||||
});
|
||||
return sub;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current number of listeners.
|
||||
*/
|
||||
get listenerCount(): number {
|
||||
return this._listeners.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispose of the emitter and all listeners.
|
||||
*/
|
||||
dispose(): void {
|
||||
this._disposed = true;
|
||||
this._listeners.clear();
|
||||
}
|
||||
}
|
||||
11
antigravity-sdk-main/src/core/index.ts
Normal file
11
antigravity-sdk-main/src/core/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Core module — types, events, disposables, errors, logging.
|
||||
*
|
||||
* @module core
|
||||
*/
|
||||
|
||||
export * from './types';
|
||||
export * from './events';
|
||||
export * from './disposable';
|
||||
export * from './errors';
|
||||
export { Logger, LogLevel } from './logger';
|
||||
84
antigravity-sdk-main/src/core/logger.ts
Normal file
84
antigravity-sdk-main/src/core/logger.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Debug logger for SDK internals.
|
||||
*
|
||||
* Respects the `antigravitySDK.debug` setting.
|
||||
*
|
||||
* @module logger
|
||||
*/
|
||||
|
||||
/**
|
||||
* Log levels for SDK logging.
|
||||
*/
|
||||
export enum LogLevel {
|
||||
Debug = 0,
|
||||
Info = 1,
|
||||
Warn = 2,
|
||||
Error = 3,
|
||||
Off = 4,
|
||||
}
|
||||
|
||||
/**
|
||||
* SDK logger with level-based filtering.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const log = new Logger('CascadeManager');
|
||||
* log.debug('Loading sessions...');
|
||||
* log.info('Found 5 sessions');
|
||||
* log.error('Failed to load', err);
|
||||
* ```
|
||||
*/
|
||||
export class Logger {
|
||||
private static _globalLevel: LogLevel = LogLevel.Warn;
|
||||
|
||||
/**
|
||||
* Set the global log level for all SDK loggers.
|
||||
*
|
||||
* @param level - Minimum level to output
|
||||
*/
|
||||
static setLevel(level: LogLevel): void {
|
||||
Logger._globalLevel = level;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a logger for a specific module.
|
||||
*
|
||||
* @param module - Module name (shown in log prefix)
|
||||
*/
|
||||
constructor(private readonly module: string) { }
|
||||
|
||||
/** Log a debug message. */
|
||||
debug(message: string, ...args: unknown[]): void {
|
||||
this._log(LogLevel.Debug, message, args);
|
||||
}
|
||||
|
||||
/** Log an informational message. */
|
||||
info(message: string, ...args: unknown[]): void {
|
||||
this._log(LogLevel.Info, message, args);
|
||||
}
|
||||
|
||||
/** Log a warning. */
|
||||
warn(message: string, ...args: unknown[]): void {
|
||||
this._log(LogLevel.Warn, message, args);
|
||||
}
|
||||
|
||||
/** Log an error. */
|
||||
error(message: string, ...args: unknown[]): void {
|
||||
this._log(LogLevel.Error, message, args);
|
||||
}
|
||||
|
||||
private _log(level: LogLevel, message: string, args: unknown[]): void {
|
||||
if (level < Logger._globalLevel) {
|
||||
return;
|
||||
}
|
||||
|
||||
const prefix = `[AntigravitySDK:${this.module}]`;
|
||||
const fn =
|
||||
level === LogLevel.Error ? console.error
|
||||
: level === LogLevel.Warn ? console.warn
|
||||
: level === LogLevel.Info ? console.info
|
||||
: console.debug;
|
||||
|
||||
fn(prefix, message, ...args);
|
||||
}
|
||||
}
|
||||
381
antigravity-sdk-main/src/core/types.ts
Normal file
381
antigravity-sdk-main/src/core/types.ts
Normal file
@@ -0,0 +1,381 @@
|
||||
/**
|
||||
* Core type definitions for Antigravity SDK.
|
||||
*
|
||||
* These types mirror the internal protobuf schemas used by Antigravity's
|
||||
* Language Server, extracted via reverse engineering of the minified source.
|
||||
*
|
||||
* @module types
|
||||
*/
|
||||
|
||||
// ─── Enums ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Terminal command auto-execution policy.
|
||||
*
|
||||
* Controls how terminal commands are handled when the agent requests execution.
|
||||
*/
|
||||
export enum TerminalExecutionPolicy {
|
||||
/** Always ask user before running */
|
||||
OFF = 1,
|
||||
/** Auto-run safe commands, ask for potentially dangerous ones */
|
||||
AUTO = 2,
|
||||
/** Always auto-run without asking */
|
||||
EAGER = 3,
|
||||
}
|
||||
|
||||
/**
|
||||
* Artifact review policy for code changes.
|
||||
*/
|
||||
export enum ArtifactReviewPolicy {
|
||||
/** Always show diff review */
|
||||
ALWAYS = 1,
|
||||
/** Skip review for simple changes */
|
||||
TURBO = 2,
|
||||
/** Automatically decide based on change complexity */
|
||||
AUTO = 3,
|
||||
}
|
||||
|
||||
/**
|
||||
* Type of a Cortex step (tool call) in a trajectory.
|
||||
*/
|
||||
export enum CortexStepType {
|
||||
RunCommand = 'RunCommand',
|
||||
WriteToFile = 'WriteToFile',
|
||||
ViewFile = 'ViewFile',
|
||||
ViewFileOutline = 'ViewFileOutline',
|
||||
ViewCodeItem = 'ViewCodeItem',
|
||||
SearchWeb = 'SearchWeb',
|
||||
ReadUrlContent = 'ReadUrlContent',
|
||||
OpenBrowserUrl = 'OpenBrowserUrl',
|
||||
ReadBrowserPage = 'ReadBrowserPage',
|
||||
ListBrowserPages = 'ListBrowserPages',
|
||||
ListDirectory = 'ListDirectory',
|
||||
FindByName = 'FindByName',
|
||||
CodebaseSearch = 'CodebaseSearch',
|
||||
GrepSearch = 'GrepSearch',
|
||||
SendCommandInput = 'SendCommandInput',
|
||||
ReadTerminal = 'ReadTerminal',
|
||||
ShellExec = 'ShellExec',
|
||||
McpTool = 'McpTool',
|
||||
InvokeSubagent = 'InvokeSubagent',
|
||||
Memory = 'Memory',
|
||||
KnowledgeGeneration = 'KnowledgeGeneration',
|
||||
UserInput = 'UserInput',
|
||||
SystemMessage = 'SystemMessage',
|
||||
PlannerResponse = 'PlannerResponse',
|
||||
Wait = 'Wait',
|
||||
ProposeCode = 'ProposeCode',
|
||||
WriteCascadeEdit = 'WriteCascadeEdit',
|
||||
}
|
||||
|
||||
/**
|
||||
* Status of a Cortex step.
|
||||
*/
|
||||
export enum StepStatus {
|
||||
/** Step is being processed */
|
||||
Running = 'running',
|
||||
/** Step completed successfully */
|
||||
Completed = 'completed',
|
||||
/** Step failed */
|
||||
Failed = 'failed',
|
||||
/** Step is waiting for user interaction */
|
||||
WaitingForUser = 'waiting_for_user',
|
||||
/** Step was cancelled */
|
||||
Cancelled = 'cancelled',
|
||||
}
|
||||
|
||||
/**
|
||||
* Type of trajectory (conversation).
|
||||
*/
|
||||
export enum TrajectoryType {
|
||||
/** Standard chat conversation */
|
||||
Chat = 'chat',
|
||||
/** Agent mode (Cascade) */
|
||||
Cascade = 'cascade',
|
||||
}
|
||||
|
||||
// ─── Interfaces ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* A single step (tool call) in a Cascade trajectory.
|
||||
*/
|
||||
export interface ICortexStep {
|
||||
/** Unique step identifier */
|
||||
readonly id: string;
|
||||
|
||||
/** Step index within the trajectory */
|
||||
readonly index: number;
|
||||
|
||||
/** Type of tool call */
|
||||
readonly type: CortexStepType;
|
||||
|
||||
/** Current status */
|
||||
readonly status: StepStatus;
|
||||
|
||||
/** Human-readable summary of what this step does */
|
||||
readonly summary: string;
|
||||
|
||||
/** Step-specific data (command line, file path, etc.) */
|
||||
readonly data: Record<string, unknown>;
|
||||
|
||||
/** Internal metadata not shown in UI */
|
||||
readonly metadata: IStepMetadata;
|
||||
|
||||
/** Timestamp when step was created */
|
||||
readonly createdAt: Date;
|
||||
|
||||
/** Timestamp when step completed (if completed) */
|
||||
readonly completedAt?: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal metadata attached to each step.
|
||||
*/
|
||||
export interface IStepMetadata {
|
||||
/** Raw protobuf fields from the server response */
|
||||
readonly rawFields: Record<string, unknown>;
|
||||
|
||||
/** Token count for this step's input */
|
||||
readonly inputTokens?: number;
|
||||
|
||||
/** Token count for this step's output */
|
||||
readonly outputTokens?: number;
|
||||
|
||||
/** Model used for this step */
|
||||
readonly model?: string;
|
||||
|
||||
/** Whether this step was auto-approved */
|
||||
readonly autoApproved?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A chat message in a conversation.
|
||||
*/
|
||||
export interface IChatMessage {
|
||||
/** Message role */
|
||||
readonly role: 'user' | 'assistant' | 'system';
|
||||
|
||||
/** Message content */
|
||||
readonly content: string;
|
||||
|
||||
/** Message ID */
|
||||
readonly id: string;
|
||||
|
||||
/** Timestamp */
|
||||
readonly createdAt: Date;
|
||||
|
||||
/** Hidden metadata */
|
||||
readonly metadata: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Information about the current context window usage.
|
||||
*/
|
||||
export interface IContextInfo {
|
||||
/** Total tokens currently in context */
|
||||
readonly totalTokens: number;
|
||||
|
||||
/** Maximum context window size */
|
||||
readonly maxTokens: number;
|
||||
|
||||
/** Usage as percentage (0-100) */
|
||||
readonly usagePercent: number;
|
||||
|
||||
/** Token breakdown by category */
|
||||
readonly breakdown: ITokenBreakdown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Token usage breakdown.
|
||||
*/
|
||||
export interface ITokenBreakdown {
|
||||
/** System prompt tokens */
|
||||
readonly system: number;
|
||||
/** User message tokens */
|
||||
readonly userMessages: number;
|
||||
/** Assistant response tokens */
|
||||
readonly assistantMessages: number;
|
||||
/** Tool call input tokens */
|
||||
readonly toolCalls: number;
|
||||
/** Tool result tokens */
|
||||
readonly toolResults: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Cascade session (conversation/trajectory).
|
||||
*/
|
||||
export interface ISessionInfo {
|
||||
/** Unique session/cascade ID */
|
||||
readonly id: string;
|
||||
|
||||
/** Session title (auto-generated or user-set) */
|
||||
readonly title: string;
|
||||
|
||||
/** When the session was created */
|
||||
readonly createdAt: Date;
|
||||
|
||||
/** When the session was last active */
|
||||
readonly lastActiveAt: Date;
|
||||
|
||||
/** Type of trajectory */
|
||||
readonly type: TrajectoryType;
|
||||
|
||||
/** Whether the session is currently active */
|
||||
readonly isActive: boolean;
|
||||
|
||||
/** Tags applied to this session */
|
||||
readonly tags: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent preferences from USS (Unified State Sync).
|
||||
*
|
||||
* All 16 sentinel keys verified from live state.vscdb on 2026-02-28.
|
||||
*/
|
||||
export interface IAgentPreferences {
|
||||
/** Terminal command auto-execution policy (terminalAutoExecutionPolicySentinelKey) */
|
||||
readonly terminalExecutionPolicy: TerminalExecutionPolicy;
|
||||
|
||||
/** Code change review policy (artifactReviewPolicySentinelKey) */
|
||||
readonly artifactReviewPolicy: ArtifactReviewPolicy;
|
||||
|
||||
/** Planning mode (planningModeSentinelKey) */
|
||||
readonly planningMode: number;
|
||||
|
||||
/** Whether strict/secure mode is enabled (secureModeSentinelKey) */
|
||||
readonly secureModeEnabled: boolean;
|
||||
|
||||
/** Whether terminal sandbox is enabled (enableTerminalSandboxSentinelKey) */
|
||||
readonly terminalSandboxEnabled: boolean;
|
||||
|
||||
/** Whether sandbox allows network access (sandboxAllowNetworkSentinelKey) */
|
||||
readonly sandboxAllowNetwork: boolean;
|
||||
|
||||
/** Whether shell integration is enabled (enableShellIntegrationSentinelKey) */
|
||||
readonly shellIntegrationEnabled: boolean;
|
||||
|
||||
/** Allow agent to access files outside workspace (allowAgentAccessNonWorkspaceFilesSentinelKey) */
|
||||
readonly allowNonWorkspaceFiles: boolean;
|
||||
|
||||
/** Allow Cascade to read .gitignore files (allowCascadeAccessGitignoreFilesSentinelKey) */
|
||||
readonly allowGitignoreAccess: boolean;
|
||||
|
||||
/** Explain and fix in current conversation (explainAndFixInCurrentConversationSentinelKey) */
|
||||
readonly explainFixInCurrentConvo: boolean;
|
||||
|
||||
/** Auto-continue on max generator invocations (autoContinueOnMaxGeneratorInvocationsSentinelKey) */
|
||||
readonly autoContinueOnMax: number;
|
||||
|
||||
/** Disable auto-open of edited files (disableAutoOpenEditedFilesSentinelKey) */
|
||||
readonly disableAutoOpenEdited: boolean;
|
||||
|
||||
/** Enable sounds for special events (enableSoundsForSpecialEventsSentinelKey) */
|
||||
readonly enableSounds: boolean;
|
||||
|
||||
/** Disable Cascade auto-fix for lint errors (disableCascadeAutoFixLintsSentinelKey) */
|
||||
readonly disableAutoFixLints: boolean;
|
||||
|
||||
/** Explicitly allowed terminal commands (terminalAllowedCommandsSentinelKey) */
|
||||
readonly allowedCommands: string[];
|
||||
|
||||
/** Explicitly denied terminal commands (terminalDeniedCommandsSentinelKey) */
|
||||
readonly deniedCommands: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Model configuration.
|
||||
*/
|
||||
export interface IModelConfig {
|
||||
/** Model identifier */
|
||||
readonly id: string;
|
||||
|
||||
/** Human-readable model name */
|
||||
readonly name: string;
|
||||
|
||||
/** Whether this model is currently selected */
|
||||
readonly isActive: boolean;
|
||||
|
||||
/** Maximum context window size in tokens */
|
||||
readonly maxContextTokens: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for creating a new Cascade session.
|
||||
*/
|
||||
export interface ICreateSessionOptions {
|
||||
/** Initial task/message to send */
|
||||
readonly task: string;
|
||||
|
||||
/** Whether to run in background (don't focus the panel) */
|
||||
readonly background?: boolean;
|
||||
|
||||
/** Model to use (defaults to current) */
|
||||
readonly model?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent state from the Agent Manager.
|
||||
*/
|
||||
export interface IAgentState {
|
||||
/** Whether the agent manager is enabled */
|
||||
readonly isEnabled: boolean;
|
||||
|
||||
/** Whether the agent is currently processing */
|
||||
readonly isProcessing: boolean;
|
||||
|
||||
/** Active cascade/conversation ID */
|
||||
readonly activeCascadeId: string | null;
|
||||
|
||||
/** Current model in use */
|
||||
readonly currentModel: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trajectory entry from getDiagnostics.recentTrajectories.
|
||||
*
|
||||
* VERIFIED 2026-02-28: getDiagnostics returns clean JSON array with:
|
||||
* { googleAgentId, trajectoryId, summary, lastStepIndex, lastModifiedTime }
|
||||
*/
|
||||
export interface ITrajectoryEntry {
|
||||
/** Conversation UUID = googleAgentId */
|
||||
readonly id: string;
|
||||
|
||||
/** Human-readable title = summary field */
|
||||
readonly title: string;
|
||||
|
||||
/** Current step index in this conversation */
|
||||
readonly stepCount: number;
|
||||
|
||||
/** Workspace URI (from USS protobuf fallback) */
|
||||
readonly workspaceUri: string;
|
||||
|
||||
/** Internal trajectory UUID (from getDiagnostics) */
|
||||
readonly trajectoryId?: string;
|
||||
|
||||
/** ISO timestamp of last modification (from getDiagnostics) */
|
||||
readonly lastModifiedTime?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Diagnostics info from `antigravity.getDiagnostics`.
|
||||
*
|
||||
* VERIFIED: returns 176KB JSON string with 8 top-level keys:
|
||||
* isRemote, systemInfo, extensionLogs, rendererLogs,
|
||||
* mainThreadLogs, agentWindowConsoleLogs, languageServerLogs,
|
||||
* recentTrajectories.
|
||||
*/
|
||||
export interface IDiagnosticsInfo {
|
||||
/** Whether IDE is running remotely (SSH) */
|
||||
readonly isRemote: boolean;
|
||||
|
||||
/** System info */
|
||||
readonly systemInfo: {
|
||||
readonly operatingSystem: string;
|
||||
readonly timestamp: string;
|
||||
readonly userEmail: string;
|
||||
readonly userName: string;
|
||||
};
|
||||
|
||||
/** Raw JSON for fields not yet typed */
|
||||
readonly raw: Record<string, unknown>;
|
||||
}
|
||||
87
antigravity-sdk-main/src/index.ts
Normal file
87
antigravity-sdk-main/src/index.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Antigravity SDK — Community SDK for Antigravity IDE.
|
||||
*
|
||||
* @packageDocumentation
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { AntigravitySDK } from 'antigravity-sdk';
|
||||
*
|
||||
* export function activate(context: vscode.ExtensionContext) {
|
||||
* const sdk = new AntigravitySDK(context);
|
||||
* await sdk.initialize();
|
||||
*
|
||||
* // Read preferences
|
||||
* const prefs = await sdk.cascade.getPreferences();
|
||||
* console.log('Terminal policy:', prefs.terminalExecutionPolicy);
|
||||
*
|
||||
* // List sessions
|
||||
* const sessions = await sdk.cascade.getSessions();
|
||||
* console.log(`${sessions.length} conversations`);
|
||||
*
|
||||
* // Get diagnostics
|
||||
* const diag = await sdk.cascade.getDiagnostics();
|
||||
* console.log(`User: ${diag.systemInfo.userName}`);
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
|
||||
// Core
|
||||
export {
|
||||
// Types
|
||||
TerminalExecutionPolicy,
|
||||
ArtifactReviewPolicy,
|
||||
CortexStepType,
|
||||
StepStatus,
|
||||
TrajectoryType,
|
||||
// Interfaces
|
||||
type ICortexStep,
|
||||
type IStepMetadata,
|
||||
type IChatMessage,
|
||||
type IContextInfo,
|
||||
type ITokenBreakdown,
|
||||
type ISessionInfo,
|
||||
type IAgentPreferences,
|
||||
type IModelConfig,
|
||||
type ICreateSessionOptions,
|
||||
type IAgentState,
|
||||
type ITrajectoryEntry,
|
||||
type IDiagnosticsInfo,
|
||||
} from './core/types';
|
||||
|
||||
export { Event, EventEmitter } from './core/events';
|
||||
export { IDisposable, DisposableStore, toDisposable } from './core/disposable';
|
||||
export {
|
||||
AntigravitySDKError,
|
||||
AntigravityNotFoundError,
|
||||
CommandExecutionError,
|
||||
StateReadError,
|
||||
SessionNotFoundError,
|
||||
} from './core/errors';
|
||||
export { Logger, LogLevel } from './core/logger';
|
||||
|
||||
// Transport
|
||||
export { CommandBridge, AntigravityCommands } from './transport/command-bridge';
|
||||
export { StateBridge, USSKeys } from './transport/state-bridge';
|
||||
export { EventMonitor, type IStateChange, type IStepCountChange, type IActiveSessionChange } from './transport/event-monitor';
|
||||
export { LSBridge, Models, type ModelId, type IHeadlessCascadeOptions, type ISendMessageOptions, type IConversationAnnotations } from './transport/ls-bridge';
|
||||
|
||||
// Cascade
|
||||
export { CascadeManager } from './cascade/cascade-manager';
|
||||
|
||||
// Integration
|
||||
export { IntegrationManager, IntegrityManager, TitleManager, IntegrationPoint } from './integration';
|
||||
export type {
|
||||
IntegrationConfig,
|
||||
IButtonIntegration,
|
||||
ITurnMetaIntegration,
|
||||
IUserBadgeIntegration,
|
||||
IBotActionIntegration,
|
||||
IDropdownIntegration,
|
||||
ITitleIntegration,
|
||||
IToastConfig,
|
||||
TurnMetric,
|
||||
} from './integration';
|
||||
|
||||
// SDK
|
||||
export { AntigravitySDK, type ISDKOptions } from './sdk';
|
||||
21
antigravity-sdk-main/src/integration/index.ts
Normal file
21
antigravity-sdk-main/src/integration/index.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Integration module — re-exports.
|
||||
* @module integration
|
||||
*/
|
||||
export { IntegrationManager } from './integration-manager';
|
||||
export { IntegrityManager } from './integrity-manager';
|
||||
export { TitleManager } from './title-manager';
|
||||
export { IntegrationPoint } from './types';
|
||||
export type {
|
||||
IntegrationConfig,
|
||||
IIntegrationManager,
|
||||
IButtonIntegration,
|
||||
ITurnMetaIntegration,
|
||||
IUserBadgeIntegration,
|
||||
IBotActionIntegration,
|
||||
IDropdownIntegration,
|
||||
ITitleIntegration,
|
||||
IToastConfig,
|
||||
IToastRow,
|
||||
TurnMetric,
|
||||
} from './types';
|
||||
704
antigravity-sdk-main/src/integration/integration-manager.ts
Normal file
704
antigravity-sdk-main/src/integration/integration-manager.ts
Normal file
@@ -0,0 +1,704 @@
|
||||
/**
|
||||
* Integration Manager — Public API for UI integration into Agent View.
|
||||
*
|
||||
* Orchestrates ScriptGenerator and WorkbenchPatcher to provide
|
||||
* a clean, developer-friendly API.
|
||||
*
|
||||
* @module integration/integration-manager
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { IntegrationManager, IntegrationPoint } from 'antigravity-sdk';
|
||||
*
|
||||
* const integrator = new IntegrationManager();
|
||||
*
|
||||
* integrator.register({
|
||||
* id: 'myStats',
|
||||
* point: IntegrationPoint.TOP_BAR,
|
||||
* icon: '📊',
|
||||
* tooltip: 'Show Stats',
|
||||
* toast: {
|
||||
* title: 'My Extension Stats',
|
||||
* rows: [{ key: 'turns:', value: 'Dynamic data here' }],
|
||||
* },
|
||||
* });
|
||||
*
|
||||
* integrator.register({
|
||||
* id: 'turnInfo',
|
||||
* point: IntegrationPoint.TURN_METADATA,
|
||||
* metrics: ['turnNumber', 'userCharCount', 'separator', 'aiCharCount', 'codeBlocks'],
|
||||
* });
|
||||
*
|
||||
* await integrator.install();
|
||||
* // Restart Antigravity to see changes
|
||||
* ```
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import { IDisposable } from '../core/disposable';
|
||||
import { Logger } from '../core/logger';
|
||||
import {
|
||||
IntegrationConfig,
|
||||
IntegrationPoint,
|
||||
IIntegrationManager,
|
||||
IButtonIntegration,
|
||||
ITurnMetaIntegration,
|
||||
IUserBadgeIntegration,
|
||||
IBotActionIntegration,
|
||||
IDropdownIntegration,
|
||||
ITitleIntegration,
|
||||
IToastConfig,
|
||||
} from './types';
|
||||
import { ScriptGenerator } from './script-generator';
|
||||
import { WorkbenchPatcher } from './workbench-patcher';
|
||||
import { IntegrityManager } from './integrity-manager';
|
||||
import { TitleManager } from './title-manager';
|
||||
import { generateTitleProxyCode } from './title-proxy';
|
||||
|
||||
const log = new Logger('IntegrationManager');
|
||||
|
||||
/**
|
||||
* Manages UI integrations into the Antigravity Agent View.
|
||||
*
|
||||
* Provides a declarative API to register integration points,
|
||||
* generates a self-contained JavaScript file, and installs it
|
||||
* into Antigravity's workbench.
|
||||
*
|
||||
* Features:
|
||||
* - **Theme-aware**: Adapts to dark/light mode automatically
|
||||
* - **Auto-repair**: Watches workbench.html and re-patches after updates
|
||||
* - **Dynamic update**: Re-generate script without re-patching workbench.html
|
||||
*/
|
||||
export class IntegrationManager implements IIntegrationManager, IDisposable {
|
||||
private readonly _configs: Map<string, IntegrationConfig> = new Map();
|
||||
private readonly _generator = new ScriptGenerator();
|
||||
private readonly _patcher: WorkbenchPatcher;
|
||||
private readonly _integrity: IntegrityManager;
|
||||
private readonly _titles = new TitleManager();
|
||||
private readonly _namespace: string;
|
||||
private _watcher: fs.FSWatcher | null = null;
|
||||
private _autoRepairDebounce: ReturnType<typeof setTimeout> | null = null;
|
||||
private _titleProxyEnabled = false;
|
||||
|
||||
/**
|
||||
* @param namespace - Unique slug that isolates this extension's files.
|
||||
* Derived automatically from `context.extension.id` when using AntigravitySDK.
|
||||
* Multiple SDK-based extensions can coexist without conflicts.
|
||||
*/
|
||||
constructor(namespace: string = 'default') {
|
||||
this._namespace = namespace;
|
||||
this._patcher = new WorkbenchPatcher(namespace);
|
||||
this._integrity = new IntegrityManager(
|
||||
this._patcher.getWorkbenchDir(),
|
||||
namespace,
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Registration ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Register a single integration point.
|
||||
*
|
||||
* @throws If an integration with the same ID already exists
|
||||
*/
|
||||
register(config: IntegrationConfig): void {
|
||||
if (this._configs.has(config.id)) {
|
||||
throw new Error(`Integration '${config.id}' is already registered`);
|
||||
}
|
||||
this._configs.set(config.id, config);
|
||||
log.debug(`Registered integration: ${config.id} (${config.point})`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register multiple integration points at once.
|
||||
*/
|
||||
registerMany(configs: IntegrationConfig[]): void {
|
||||
for (const c of configs) {
|
||||
this.register(c);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a registered integration by ID.
|
||||
*/
|
||||
unregister(id: string): void {
|
||||
this._configs.delete(id);
|
||||
log.debug(`Unregistered integration: ${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered integrations.
|
||||
*/
|
||||
getRegistered(): ReadonlyArray<IntegrationConfig> {
|
||||
return Array.from(this._configs.values());
|
||||
}
|
||||
|
||||
// ─── Convenience methods (fluent API) ──────────────────────────────
|
||||
|
||||
/**
|
||||
* Add a button to the top bar (near +, refresh icons).
|
||||
*/
|
||||
addTopBarButton(id: string, icon: string, tooltip?: string, toast?: IToastConfig): this {
|
||||
this.register({
|
||||
id,
|
||||
point: IntegrationPoint.TOP_BAR,
|
||||
icon,
|
||||
tooltip,
|
||||
toast,
|
||||
} as IButtonIntegration);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a button to the top-right corner (before X).
|
||||
*/
|
||||
addTopRightButton(id: string, icon: string, tooltip?: string, toast?: IToastConfig): this {
|
||||
this.register({
|
||||
id,
|
||||
point: IntegrationPoint.TOP_RIGHT,
|
||||
icon,
|
||||
tooltip,
|
||||
toast,
|
||||
} as IButtonIntegration);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a button next to the send/voice buttons.
|
||||
*/
|
||||
addInputButton(id: string, icon: string, tooltip?: string, toast?: IToastConfig): this {
|
||||
this.register({
|
||||
id,
|
||||
point: IntegrationPoint.INPUT_AREA,
|
||||
icon,
|
||||
tooltip,
|
||||
toast,
|
||||
} as IButtonIntegration);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an icon to the bottom icon row (file, terminal, etc.).
|
||||
*/
|
||||
addBottomIcon(id: string, icon: string, tooltip?: string, toast?: IToastConfig): this {
|
||||
this.register({
|
||||
id,
|
||||
point: IntegrationPoint.BOTTOM_ICONS,
|
||||
icon,
|
||||
tooltip,
|
||||
toast,
|
||||
} as IButtonIntegration);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable per-turn metadata display.
|
||||
*/
|
||||
addTurnMetadata(id: string, metrics: ITurnMetaIntegration['metrics'], clickable = true): this {
|
||||
this.register({
|
||||
id,
|
||||
point: IntegrationPoint.TURN_METADATA,
|
||||
metrics,
|
||||
clickable,
|
||||
} as ITurnMetaIntegration);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add character count badges to user messages.
|
||||
*/
|
||||
addUserBadges(id: string, display: IUserBadgeIntegration['display'] = 'charCount'): this {
|
||||
this.register({
|
||||
id,
|
||||
point: IntegrationPoint.USER_BADGE,
|
||||
display,
|
||||
} as IUserBadgeIntegration);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an action button next to Good/Bad feedback.
|
||||
*/
|
||||
addBotAction(id: string, icon: string, label: string, toast?: IToastConfig): this {
|
||||
this.register({
|
||||
id,
|
||||
point: IntegrationPoint.BOT_ACTION,
|
||||
icon,
|
||||
label,
|
||||
toast,
|
||||
} as IBotActionIntegration);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add item(s) to the 3-dot dropdown menu.
|
||||
*/
|
||||
addDropdownItem(id: string, label: string, icon?: string, toast?: IToastConfig, separator = false): this {
|
||||
this.register({
|
||||
id,
|
||||
point: IntegrationPoint.DROPDOWN_MENU,
|
||||
label,
|
||||
icon,
|
||||
toast,
|
||||
separator,
|
||||
} as IDropdownIntegration);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable chat title interaction.
|
||||
*/
|
||||
addTitleInteraction(id: string, interaction: ITitleIntegration['interaction'] = 'dblclick', hint?: string, toast?: IToastConfig): this {
|
||||
this.register({
|
||||
id,
|
||||
point: IntegrationPoint.CHAT_TITLE,
|
||||
interaction,
|
||||
hint,
|
||||
toast,
|
||||
} as ITitleIntegration);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ─── Title Proxy ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Enable the title proxy feature.
|
||||
*
|
||||
* Adds renderer-side code that intercepts the summaries provider
|
||||
* and injects custom chat titles. Uses structural matching to find
|
||||
* the provider (obfuscation-safe).
|
||||
*
|
||||
* After enabling, call `install()` or `updateScript()` to apply.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const sdk = new AntigravitySDK(context);
|
||||
* await sdk.initialize();
|
||||
*
|
||||
* sdk.integration.enableTitleProxy();
|
||||
* await sdk.integration.install();
|
||||
*
|
||||
* // Now rename from extension host:
|
||||
* sdk.integration.titles.rename(cascadeId, 'My Custom Title');
|
||||
* ```
|
||||
*/
|
||||
enableTitleProxy(): this {
|
||||
this._titleProxyEnabled = true;
|
||||
if (this._patcher.isAvailable()) {
|
||||
this._titles.initialize(this._patcher.getWorkbenchDir(), this._namespace);
|
||||
}
|
||||
log.info('Title proxy enabled');
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Access the title manager for programmatic title control.
|
||||
*
|
||||
* Requires `enableTitleProxy()` to be called first.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* sdk.integration.titles.rename(cascadeId, 'My Title');
|
||||
* sdk.integration.titles.remove(cascadeId);
|
||||
* const all = sdk.integration.titles.getAll();
|
||||
* ```
|
||||
*/
|
||||
get titles(): TitleManager {
|
||||
if (!this._titleProxyEnabled) {
|
||||
log.warn('Title proxy not enabled. Call enableTitleProxy() first.');
|
||||
}
|
||||
return this._titles;
|
||||
}
|
||||
|
||||
// ─── Build & Install ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Generate the integration script from all registered configs.
|
||||
*
|
||||
* If title proxy is enabled, appends the title proxy renderer code.
|
||||
*
|
||||
* @returns Complete JavaScript code as a string
|
||||
*/
|
||||
build(): string {
|
||||
const configs = Array.from(this._configs.values());
|
||||
if (configs.length === 0 && !this._titleProxyEnabled) {
|
||||
throw new Error('No integration points registered and title proxy not enabled');
|
||||
}
|
||||
|
||||
let script = '';
|
||||
if (configs.length > 0) {
|
||||
log.info(`Building script for ${configs.length} integration(s)`);
|
||||
script = this._generator.generate(configs);
|
||||
}
|
||||
|
||||
if (this._titleProxyEnabled) {
|
||||
log.info('Appending title proxy code');
|
||||
script += '\n' + generateTitleProxyCode(this._namespace);
|
||||
}
|
||||
|
||||
return script;
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the generated script into workbench.html.
|
||||
*
|
||||
* For seamless hot-reload behavior, use `installSeamless()` instead.
|
||||
*
|
||||
* @returns true if the script content actually changed on disk
|
||||
*/
|
||||
async install(): Promise<boolean> {
|
||||
if (!this._patcher.isAvailable()) {
|
||||
throw new Error('Antigravity workbench not found. Is Antigravity installed?');
|
||||
}
|
||||
|
||||
const script = this.build();
|
||||
|
||||
// Read existing script to detect changes
|
||||
const scriptPath = this._patcher.getScriptPath();
|
||||
let oldContent = '';
|
||||
try {
|
||||
if (fs.existsSync(scriptPath)) {
|
||||
oldContent = fs.readFileSync(scriptPath, 'utf8');
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
|
||||
this._patcher.install(script);
|
||||
this._integrity.suppressCheck();
|
||||
this._patcher.writeHeartbeat();
|
||||
|
||||
const changed = oldContent !== script;
|
||||
log.info(
|
||||
`Installed integration (${this._configs.size} points, titleProxy: ${this._titleProxyEnabled}) -> ${scriptPath} [${changed ? 'CHANGED' : 'unchanged'}]`,
|
||||
);
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Seamless install — handles everything automatically.
|
||||
*
|
||||
* This is the **recommended** install method for extension developers.
|
||||
* It handles the entire lifecycle:
|
||||
*
|
||||
* 1. **First install:** Writes script + patches HTML + prompts user to reload
|
||||
* 2. **Update:** Compares content, if changed → auto-reloads window (no prompt)
|
||||
* 3. **No change:** Does nothing
|
||||
*
|
||||
* The developer never needs to think about reload.
|
||||
*
|
||||
* @param executeCommand - Function to execute VS Code commands
|
||||
* (pass `vscode.commands.executeCommand` or equivalent)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const sdk = new AntigravitySDK(context);
|
||||
* await sdk.initialize();
|
||||
*
|
||||
* sdk.integration.enableTitleProxy();
|
||||
* // That's it. SDK handles install, reload, everything.
|
||||
* await sdk.integration.installSeamless(
|
||||
* (cmd) => vscode.commands.executeCommand(cmd),
|
||||
* (msg, ...items) => vscode.window.showInformationMessage(msg, ...items),
|
||||
* );
|
||||
* ```
|
||||
*/
|
||||
async installSeamless(
|
||||
executeCommand: (command: string) => Thenable<any>,
|
||||
showMessage?: (message: string, ...items: string[]) => Thenable<string | undefined>,
|
||||
): Promise<void> {
|
||||
const wasInstalled = this._patcher.isInstalled();
|
||||
|
||||
// Snapshot old content before install
|
||||
const scriptPath = this._patcher.getScriptPath();
|
||||
let oldContent = '';
|
||||
try {
|
||||
if (fs.existsSync(scriptPath)) {
|
||||
oldContent = fs.readFileSync(scriptPath, 'utf8');
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
|
||||
const changed = await this.install();
|
||||
|
||||
if (!wasInstalled) {
|
||||
// First install: prompt user
|
||||
log.info('First install. Prompting for reload.');
|
||||
if (showMessage) {
|
||||
const action = await showMessage(
|
||||
'Better Antigravity installed. Reload to activate.',
|
||||
'Reload Now',
|
||||
);
|
||||
if (action === 'Reload Now') {
|
||||
await executeCommand('workbench.action.reloadWindow');
|
||||
}
|
||||
}
|
||||
} else if (changed) {
|
||||
// Update: auto-reload (no prompt)
|
||||
log.info('Script changed on disk. Auto-reloading window...');
|
||||
// Small delay to let extension finish activation
|
||||
setTimeout(() => executeCommand('workbench.action.reloadWindow'), 500);
|
||||
} else {
|
||||
log.debug('Script unchanged. No reload needed.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the integration from workbench.html.
|
||||
*
|
||||
* ⚠️ Requires Antigravity restart to take effect.
|
||||
*/
|
||||
async uninstall(): Promise<void> {
|
||||
this._patcher.uninstall();
|
||||
this._integrity.releaseCheck();
|
||||
this._patcher.removeHeartbeat();
|
||||
this.disableAutoRepair();
|
||||
log.info('Uninstalled integration. Restart Antigravity to apply.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an integration is currently installed.
|
||||
*/
|
||||
isInstalled(): boolean {
|
||||
return this._patcher.isInstalled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Signal that the extension is active.
|
||||
*
|
||||
* Call this in your extension's `activate()` function.
|
||||
* The integration script checks for this heartbeat;
|
||||
* if it's missing or stale (>48h), the script won't start.
|
||||
*
|
||||
* This prevents orphaned integrations from running after
|
||||
* an extension is disabled or uninstalled.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* export function activate(context: vscode.ExtensionContext) {
|
||||
* const sdk = new AntigravitySDK(context);
|
||||
* sdk.integration.signalActive();
|
||||
* // ...
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
signalActive(): void {
|
||||
this._patcher.writeHeartbeat();
|
||||
log.debug('Heartbeat refreshed');
|
||||
}
|
||||
|
||||
// ─── Dynamic Update ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Re-generate and overwrite the integration script without re-patching workbench.html.
|
||||
*
|
||||
* Use this after registering/unregistering integration points at runtime.
|
||||
* The script file is updated in-place; the next Antigravity restart
|
||||
* will pick up the changes. workbench.html <script> tag is unchanged.
|
||||
*
|
||||
* @returns true if script was updated
|
||||
*/
|
||||
updateScript(): boolean {
|
||||
if (!this._patcher.isInstalled()) {
|
||||
log.warn('Cannot update script — integration is not installed');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const script = this.build();
|
||||
fs.writeFileSync(this._patcher.getScriptPath(), script, 'utf8');
|
||||
log.info(`Script updated (${this._configs.size} points)`);
|
||||
return true;
|
||||
} catch (err) {
|
||||
log.error('Failed to update script', err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Auto-Repair ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Enable auto-repair: watches workbench.html for changes
|
||||
* and automatically re-applies the integration patch.
|
||||
*
|
||||
* This handles Antigravity updates that overwrite workbench.html.
|
||||
* The watcher detects when the file changes and re-patches it
|
||||
* if the integration marker is missing.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const integrator = new IntegrationManager();
|
||||
* integrator.useDemoPreset();
|
||||
* await integrator.install();
|
||||
* integrator.enableAutoRepair(); // Survive Antigravity updates
|
||||
* ```
|
||||
*/
|
||||
enableAutoRepair(): void {
|
||||
if (this._watcher) return;
|
||||
|
||||
const htmlPath = this._patcher.getWorkbenchDir() + '\\workbench.html';
|
||||
if (!fs.existsSync(htmlPath)) {
|
||||
log.warn('Cannot enable auto-repair — workbench.html not found');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this._watcher = fs.watch(htmlPath, (eventType) => {
|
||||
if (eventType !== 'change') return;
|
||||
|
||||
// Debounce — Antigravity may write multiple times
|
||||
if (this._autoRepairDebounce) clearTimeout(this._autoRepairDebounce);
|
||||
this._autoRepairDebounce = setTimeout(() => {
|
||||
this._tryRepair();
|
||||
}, 2000);
|
||||
});
|
||||
|
||||
log.info('Auto-repair enabled — watching workbench.html');
|
||||
} catch (err) {
|
||||
log.error('Failed to enable auto-repair', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable auto-repair watcher.
|
||||
*/
|
||||
disableAutoRepair(): void {
|
||||
if (this._watcher) {
|
||||
this._watcher.close();
|
||||
this._watcher = null;
|
||||
log.info('Auto-repair disabled');
|
||||
}
|
||||
if (this._autoRepairDebounce) {
|
||||
clearTimeout(this._autoRepairDebounce);
|
||||
this._autoRepairDebounce = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether auto-repair is active.
|
||||
*/
|
||||
get isAutoRepairEnabled(): boolean {
|
||||
return this._watcher !== null;
|
||||
}
|
||||
|
||||
private _tryRepair(): void {
|
||||
try {
|
||||
if (this._patcher.isInstalled()) {
|
||||
log.debug('Auto-repair: integration still present, no action needed');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._configs.size === 0) {
|
||||
log.debug('Auto-repair: no configs registered, skipping');
|
||||
return;
|
||||
}
|
||||
|
||||
log.info('Auto-repair: integration lost (Antigravity update?), re-patching...');
|
||||
const script = this.build();
|
||||
this._patcher.install(script);
|
||||
this._integrity.repair();
|
||||
log.info('Auto-repair: re-patched successfully. Restart Antigravity.');
|
||||
} catch (err) {
|
||||
log.error('Auto-repair failed', err);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Preset ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Register the Demo preset — a complete demo of all 9 integration points.
|
||||
* Useful for testing and as a reference implementation.
|
||||
*/
|
||||
useDemoPreset(): this {
|
||||
this.addTopBarButton('demo_overview', '\u{1F4E1}', 'SDK: Session Overview', {
|
||||
title: 'Session Overview',
|
||||
badge: { text: 'TOP_BAR', bgColor: 'rgba(79,195,247,.2)', textColor: '#4fc3f7' },
|
||||
rows: [
|
||||
{ key: 'location:', value: 'Header icon bar' },
|
||||
{ key: 'use case:', value: 'Session overview, navigation' },
|
||||
],
|
||||
});
|
||||
|
||||
this.addTopRightButton('demo_perf', '\u26A1', 'SDK: Performance', {
|
||||
title: 'Performance',
|
||||
badge: { text: 'TOP_RIGHT', bgColor: 'rgba(255,193,7,.2)', textColor: '#ffd54f' },
|
||||
rows: [
|
||||
{ key: 'location:', value: 'Top right, before close' },
|
||||
{ key: 'use case:', value: 'Status indicator' },
|
||||
],
|
||||
});
|
||||
|
||||
this.addInputButton('demo_stats', '\u{1F4CA}', 'SDK: Stats', {
|
||||
title: 'Input Stats',
|
||||
badge: { text: 'INPUT_AREA', bgColor: 'rgba(76,175,80,.2)', textColor: '#81c784' },
|
||||
rows: [
|
||||
{ key: 'location:', value: 'Next to send button' },
|
||||
{ key: 'use case:', value: 'Token counter, analytics' },
|
||||
],
|
||||
});
|
||||
|
||||
this.addBottomIcon('demo_actions', '\u2630', 'SDK: Quick Actions', {
|
||||
title: 'Quick Actions',
|
||||
badge: { text: 'BOTTOM_ICONS', bgColor: 'rgba(255,152,0,.2)', textColor: '#ffb74d' },
|
||||
rows: [
|
||||
{ key: 'location:', value: 'Bottom icon row' },
|
||||
{ key: 'use case:', value: 'Mode switches, quick actions' },
|
||||
],
|
||||
});
|
||||
|
||||
this.addTurnMetadata('demo_turns', [
|
||||
'turnNumber',
|
||||
'userCharCount',
|
||||
'separator',
|
||||
'aiCharCount',
|
||||
'codeBlocks',
|
||||
'thinkingIndicator',
|
||||
]);
|
||||
|
||||
this.addUserBadges('demo_ubadge', 'charCount');
|
||||
|
||||
this.addBotAction('demo_inspect', '\u{1F50D}', 'inspect', {
|
||||
title: 'Response Inspector',
|
||||
badge: { text: 'BOT_ACTION', bgColor: 'rgba(156,39,176,.2)', textColor: '#ce93d8' },
|
||||
rows: [
|
||||
{ key: 'location:', value: 'Next to Good/Bad' },
|
||||
{ key: 'use case:', value: 'Response analysis' },
|
||||
],
|
||||
});
|
||||
|
||||
this.addDropdownItem('demo_menu_stats', 'SDK Stats', '\u{1F4CA}', {
|
||||
title: 'Extended Stats',
|
||||
badge: { text: 'DROPDOWN', bgColor: 'rgba(233,30,99,.2)', textColor: '#f48fb1' },
|
||||
rows: [
|
||||
{ key: 'location:', value: '3-dot dropdown menu' },
|
||||
{ key: 'use case:', value: 'Extended actions' },
|
||||
],
|
||||
}, true);
|
||||
|
||||
this.addDropdownItem('demo_menu_debug', 'SDK Debug', '\u{1F9EA}', {
|
||||
title: 'Debug Info',
|
||||
badge: { text: 'DEBUG', bgColor: 'rgba(255,87,34,.2)', textColor: '#ff8a65' },
|
||||
rows: [
|
||||
{ key: 'location:', value: '3-dot dropdown menu' },
|
||||
{ key: 'use case:', value: 'Debug, diagnostics' },
|
||||
],
|
||||
});
|
||||
|
||||
this.addTitleInteraction('demo_title', 'dblclick', 'dblclick', {
|
||||
title: 'Chat Title',
|
||||
badge: { text: 'TITLE', bgColor: 'rgba(0,150,136,.2)', textColor: '#80cbc4' },
|
||||
rows: [
|
||||
{ key: 'location:', value: 'Conversation title' },
|
||||
{ key: 'use case:', value: 'Rename, bookmark' },
|
||||
],
|
||||
});
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// ─── Dispose ───────────────────────────────────────────────────────
|
||||
|
||||
dispose(): void {
|
||||
this.disableAutoRepair();
|
||||
this._configs.clear();
|
||||
this._titles.dispose();
|
||||
}
|
||||
}
|
||||
270
antigravity-sdk-main/src/integration/integrity-manager.ts
Normal file
270
antigravity-sdk-main/src/integration/integrity-manager.ts
Normal file
@@ -0,0 +1,270 @@
|
||||
/**
|
||||
* Integrity Manager — Suppress Antigravity's "corrupt installation" warnings.
|
||||
*
|
||||
* When the SDK patches workbench files, Antigravity's IntegrityService detects
|
||||
* checksum mismatches and shows two warnings:
|
||||
* 1. Console WARN ("Installation has been modified on disk")
|
||||
* 2. UI Notification ("Your Antigravity installation appears to be corrupt")
|
||||
*
|
||||
* This class updates ALL mismatched SHA256 hashes in product.json, so
|
||||
* IntegrityService sees isPure=true and produces no warnings at all.
|
||||
*
|
||||
* Handles not just workbench.html but also workbench.desktop.main.js (auto-run fix),
|
||||
* workbench-jetski-agent.html (agent manager patching), and any other modified files.
|
||||
*
|
||||
* Multi-extension coordination: a registry file (.ag-sdk-integrity.json)
|
||||
* in the workbench directory tracks active SDK namespaces and the original
|
||||
* hashes, so the last extension to uninstall restores the original state.
|
||||
*
|
||||
* @module integration/integrity-manager
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
|
||||
import * as crypto from 'crypto';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { Logger } from '../core/logger';
|
||||
|
||||
const log = new Logger('IntegrityManager');
|
||||
|
||||
/** Coordination registry stored in the workbench directory. */
|
||||
interface IIntegrityRegistry {
|
||||
/** Active SDK namespace slugs. */
|
||||
namespaces: string[];
|
||||
/** Original product.json hashes for ALL checksummed files (before any patching). */
|
||||
originalHashes: Record<string, string>;
|
||||
}
|
||||
|
||||
/** Registry filename — lives next to workbench.html. */
|
||||
const REGISTRY_FILENAME = '.ag-sdk-integrity.json';
|
||||
|
||||
/**
|
||||
* Manages integrity check suppression for Antigravity's IntegrityService.
|
||||
*
|
||||
* Call `suppressCheck()` after any file patching (workbench.html, main.js, etc.).
|
||||
* It scans ALL files listed in product.json checksums, recomputes hashes for
|
||||
* any that have changed, and updates product.json. IntegrityService will see
|
||||
* `isPure = true` on next restart, producing zero warnings.
|
||||
*/
|
||||
export class IntegrityManager {
|
||||
private readonly _productJsonPath: string;
|
||||
private readonly _appOutDir: string;
|
||||
private readonly _registryPath: string;
|
||||
private readonly _namespace: string;
|
||||
|
||||
/**
|
||||
* @param workbenchDir — Absolute path to the workbench directory
|
||||
* (e.g. `%LOCALAPPDATA%/Programs/Antigravity/resources/app/out/vs/code/electron-browser/workbench/`)
|
||||
* @param namespace — Unique slug for this extension (e.g. 'kanezal-better-antigravity')
|
||||
*/
|
||||
constructor(workbenchDir: string, namespace: string) {
|
||||
this._namespace = namespace;
|
||||
this._registryPath = path.join(workbenchDir, REGISTRY_FILENAME);
|
||||
|
||||
// product.json is at resources/app/product.json
|
||||
// workbenchDir is resources/app/out/vs/code/electron-browser/workbench/
|
||||
const appDir = path.resolve(workbenchDir, '..', '..', '..', '..', '..');
|
||||
this._productJsonPath = path.join(appDir, 'product.json');
|
||||
this._appOutDir = path.join(appDir, 'out');
|
||||
}
|
||||
|
||||
/**
|
||||
* Suppress the integrity check by updating ALL mismatched hashes in product.json.
|
||||
*
|
||||
* Scans every file listed in product.json checksums, recomputes SHA256 for each,
|
||||
* and updates any that have changed. This handles not just workbench.html but also
|
||||
* workbench.desktop.main.js (auto-run fix), jetskiAgent files, etc.
|
||||
*
|
||||
* Call this after any file patching. Safe to call multiple times.
|
||||
*/
|
||||
suppressCheck(): void {
|
||||
try {
|
||||
if (!fs.existsSync(this._productJsonPath)) {
|
||||
log.warn(`product.json not found at ${this._productJsonPath}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const productJson = JSON.parse(fs.readFileSync(this._productJsonPath, 'utf8'));
|
||||
if (!productJson.checksums) {
|
||||
log.debug('No checksums in product.json — nothing to update');
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. Load or create registry, register this namespace
|
||||
const registry = this._readRegistry();
|
||||
if (!registry.namespaces.includes(this._namespace)) {
|
||||
registry.namespaces.push(this._namespace);
|
||||
}
|
||||
|
||||
// 2. Scan ALL checksummed files, save originals & update mismatches
|
||||
let updatedCount = 0;
|
||||
for (const [relPath, storedHash] of Object.entries(productJson.checksums) as [string, string][]) {
|
||||
const filePath = path.join(this._appOutDir, relPath);
|
||||
|
||||
let actualHash: string;
|
||||
try {
|
||||
const content = fs.readFileSync(filePath);
|
||||
actualHash = this._computeHash(content);
|
||||
} catch {
|
||||
// File not found — skip (don't break other checks)
|
||||
continue;
|
||||
}
|
||||
|
||||
if (actualHash !== storedHash) {
|
||||
// Save original hash if we haven't already
|
||||
if (!(relPath in registry.originalHashes)) {
|
||||
registry.originalHashes[relPath] = storedHash;
|
||||
log.debug(`Saved original hash for ${relPath}`);
|
||||
}
|
||||
|
||||
productJson.checksums[relPath] = actualHash;
|
||||
updatedCount++;
|
||||
log.info(`Updated hash: ${relPath} (${storedHash.substring(0, 8)}... -> ${actualHash.substring(0, 8)}...)`);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Write registry
|
||||
this._writeRegistry(registry);
|
||||
|
||||
// 4. Write product.json if anything changed
|
||||
if (updatedCount > 0) {
|
||||
fs.writeFileSync(this._productJsonPath, JSON.stringify(productJson, null, '\t'), 'utf8');
|
||||
log.info(`Updated ${updatedCount} hash(es) in product.json`);
|
||||
} else {
|
||||
log.debug('All hashes already match — no update needed');
|
||||
}
|
||||
} catch (err) {
|
||||
log.error('Failed to suppress integrity check', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the integrity check suppression.
|
||||
*
|
||||
* Call this when uninstalling the integration. If no other SDK namespaces
|
||||
* remain active, restores all original hashes in product.json.
|
||||
*/
|
||||
releaseCheck(): void {
|
||||
try {
|
||||
const registry = this._readRegistry();
|
||||
|
||||
// Remove this namespace
|
||||
registry.namespaces = registry.namespaces.filter(ns => ns !== this._namespace);
|
||||
this._writeRegistry(registry);
|
||||
|
||||
if (registry.namespaces.length > 0) {
|
||||
// Other SDK extensions still active — recompute all hashes
|
||||
log.debug(`${registry.namespaces.length} other namespace(s) still active, recomputing hashes`);
|
||||
this.suppressCheck();
|
||||
return;
|
||||
}
|
||||
|
||||
// Last extension uninstalling — restore ALL original hashes
|
||||
if (Object.keys(registry.originalHashes).length > 0) {
|
||||
this._restoreOriginalHashes(registry.originalHashes);
|
||||
log.info(`Restored ${Object.keys(registry.originalHashes).length} original hash(es)`);
|
||||
}
|
||||
|
||||
// Clean up registry file
|
||||
this._deleteRegistry();
|
||||
} catch (err) {
|
||||
log.error('Failed to release integrity check', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-apply integrity suppression after auto-repair.
|
||||
*
|
||||
* Call this after auto-repair has re-patched files
|
||||
* (e.g. after an AG update that overwrote workbench files).
|
||||
*/
|
||||
repair(): void {
|
||||
log.info('Repairing integrity check suppression...');
|
||||
this.suppressCheck();
|
||||
}
|
||||
|
||||
// ── Private helpers ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Compute SHA256 hash matching Antigravity's ChecksumService format:
|
||||
* base64 WITHOUT trailing '=' padding.
|
||||
*/
|
||||
private _computeHash(content: Buffer): string {
|
||||
return crypto.createHash('sha256')
|
||||
.update(content)
|
||||
.digest('base64')
|
||||
.replace(/=+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore all original hashes in product.json.
|
||||
*/
|
||||
private _restoreOriginalHashes(originalHashes: Record<string, string>): void {
|
||||
if (!fs.existsSync(this._productJsonPath)) return;
|
||||
|
||||
const productJson = JSON.parse(fs.readFileSync(this._productJsonPath, 'utf8'));
|
||||
if (!productJson.checksums) return;
|
||||
|
||||
for (const [relPath, hash] of Object.entries(originalHashes)) {
|
||||
if (relPath in productJson.checksums) {
|
||||
productJson.checksums[relPath] = hash;
|
||||
}
|
||||
}
|
||||
|
||||
fs.writeFileSync(this._productJsonPath, JSON.stringify(productJson, null, '\t'), 'utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the coordination registry from disk.
|
||||
*/
|
||||
private _readRegistry(): IIntegrityRegistry {
|
||||
try {
|
||||
if (fs.existsSync(this._registryPath)) {
|
||||
const raw = fs.readFileSync(this._registryPath, 'utf8');
|
||||
const data = JSON.parse(raw);
|
||||
|
||||
// Migrate from old format (single originalHash) to new (originalHashes map)
|
||||
let originalHashes: Record<string, string> = {};
|
||||
if (data.originalHashes && typeof data.originalHashes === 'object') {
|
||||
originalHashes = data.originalHashes;
|
||||
} else if (typeof data.originalHash === 'string') {
|
||||
// Legacy v1.5.0 format: single hash for workbench.html
|
||||
originalHashes['vs/code/electron-browser/workbench/workbench.html'] = data.originalHash;
|
||||
}
|
||||
|
||||
return {
|
||||
namespaces: Array.isArray(data.namespaces) ? data.namespaces : [],
|
||||
originalHashes,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Corrupt or inaccessible — start fresh
|
||||
}
|
||||
return { namespaces: [], originalHashes: {} };
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the coordination registry to disk.
|
||||
*/
|
||||
private _writeRegistry(registry: IIntegrityRegistry): void {
|
||||
try {
|
||||
fs.writeFileSync(this._registryPath, JSON.stringify(registry, null, 2), 'utf8');
|
||||
} catch (err) {
|
||||
log.error('Failed to write integrity registry', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the coordination registry file.
|
||||
*/
|
||||
private _deleteRegistry(): void {
|
||||
try {
|
||||
if (fs.existsSync(this._registryPath)) {
|
||||
fs.unlinkSync(this._registryPath);
|
||||
}
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
554
antigravity-sdk-main/src/integration/script-generator.ts
Normal file
554
antigravity-sdk-main/src/integration/script-generator.ts
Normal file
@@ -0,0 +1,554 @@
|
||||
/**
|
||||
* Script Generator — Builds self-contained JS from integration configs.
|
||||
*
|
||||
* Generates a Trusted Types-safe integration script that:
|
||||
* - Uses ONLY createElement/textContent (no innerHTML)
|
||||
* - Uses MutationObserver for dynamic content
|
||||
* - Is fully self-contained (runs in renderer, no Node.js APIs)
|
||||
*
|
||||
* @module integration/script-generator
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
|
||||
import { Selectors, AG_PREFIX, AG_DATA_ATTR } from './selectors';
|
||||
import {
|
||||
IntegrationConfig,
|
||||
IntegrationPoint,
|
||||
IToastConfig,
|
||||
IToastRow,
|
||||
TurnMetric,
|
||||
IButtonIntegration,
|
||||
ITurnMetaIntegration,
|
||||
IUserBadgeIntegration,
|
||||
IBotActionIntegration,
|
||||
IDropdownIntegration,
|
||||
ITitleIntegration,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Generates a self-contained JavaScript integration script
|
||||
* from an array of IntegrationConfig objects.
|
||||
*/
|
||||
export class ScriptGenerator {
|
||||
/**
|
||||
* Generate the complete integration script.
|
||||
*
|
||||
* @param configs — Registered integration configurations
|
||||
* @returns — Complete JS code as a string
|
||||
*/
|
||||
generate(configs: IntegrationConfig[]): string {
|
||||
const parts: string[] = [];
|
||||
|
||||
parts.push(this._header());
|
||||
parts.push(this._css(configs));
|
||||
parts.push(this._helpers());
|
||||
parts.push(this._toast());
|
||||
parts.push(this._stats());
|
||||
|
||||
// Generate code for each integration point
|
||||
const grouped = this._groupByPoint(configs);
|
||||
|
||||
for (const [point, cfgs] of Object.entries(grouped)) {
|
||||
parts.push(this._generatePoint(point as IntegrationPoint, cfgs));
|
||||
}
|
||||
|
||||
parts.push(this._mainLoop(Object.keys(grouped) as IntegrationPoint[]));
|
||||
parts.push(this._footer());
|
||||
|
||||
return parts.join('\n');
|
||||
}
|
||||
|
||||
// ─── Grouping ──────────────────────────────────────────────────────
|
||||
|
||||
private _groupByPoint(configs: IntegrationConfig[]): Record<string, IntegrationConfig[]> {
|
||||
const groups: Record<string, IntegrationConfig[]> = {};
|
||||
for (const c of configs) {
|
||||
if (c.enabled === false) continue;
|
||||
if (!groups[c.point]) groups[c.point] = [];
|
||||
groups[c.point].push(c);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
// ─── Code Sections ────────────────────────────────────────────────
|
||||
|
||||
private _header(): string {
|
||||
return `(function agSDK(){
|
||||
'use strict';
|
||||
if(window.__agSDK)return;
|
||||
window.__agSDK=true;
|
||||
|
||||
// ─── Theme Detection ───
|
||||
var _isDark=document.body.classList.contains('vscode-dark')||document.body.classList.contains('vscode-high-contrast');
|
||||
var _theme={
|
||||
bg:_isDark?'rgba(25,25,30,.95)':'rgba(245,245,250,.95)',
|
||||
fg:_isDark?'#ccc':'#333',
|
||||
fgDim:_isDark?'rgba(200,200,200,.45)':'rgba(80,80,80,.5)',
|
||||
fgHover:_isDark?'rgba(200,200,200,.8)':'rgba(40,40,40,.9)',
|
||||
accent:_isDark?'#4fc3f7':'#0288d1',
|
||||
accentBg:_isDark?'rgba(79,195,247,.12)':'rgba(2,136,209,.08)',
|
||||
success:_isDark?'#81c784':'#388e3c',
|
||||
successBg:_isDark?'rgba(76,175,80,.1)':'rgba(56,142,60,.06)',
|
||||
warn:_isDark?'#ffb74d':'#e65100',
|
||||
border:_isDark?'rgba(79,195,247,.06)':'rgba(0,0,0,.06)',
|
||||
borderHover:_isDark?'rgba(79,195,247,.2)':'rgba(2,136,209,.15)',
|
||||
sep:_isDark?'rgba(255,255,255,.06)':'rgba(0,0,0,.06)',
|
||||
shadow:_isDark?'rgba(0,0,0,.5)':'rgba(0,0,0,.15)',
|
||||
metaBg:_isDark?'linear-gradient(135deg,rgba(79,195,247,.03),rgba(156,39,176,.02))':'linear-gradient(135deg,rgba(2,136,209,.03),rgba(123,31,162,.02))',
|
||||
metaBgHover:_isDark?'linear-gradient(135deg,rgba(79,195,247,.07),rgba(156,39,176,.05))':'linear-gradient(135deg,rgba(2,136,209,.07),rgba(123,31,162,.05))'
|
||||
};
|
||||
// Watch for theme changes (VS Code toggles body classes)
|
||||
new MutationObserver(function(){var newDark=document.body.classList.contains('vscode-dark');if(newDark!==_isDark){location.reload();}}).observe(document.body,{attributes:true,attributeFilter:['class']});
|
||||
`;
|
||||
}
|
||||
|
||||
private _footer(): string {
|
||||
// The heartbeat file is in the same directory as the script.
|
||||
// We use sync XHR (allowed in renderer since we're in a script tag,
|
||||
// not a module) to check the file before starting.
|
||||
// Max age: 48 hours (172800000ms) — enough to survive normal restarts
|
||||
// but catches disabled extensions reliably.
|
||||
return `
|
||||
var _heartbeatMaxAge=172800000;
|
||||
function checkHeartbeat(){
|
||||
try{
|
||||
var xhr=new XMLHttpRequest();
|
||||
xhr.open('GET','./ag-sdk-heartbeat?t='+Date.now(),false);
|
||||
xhr.send();
|
||||
if(xhr.status!==200)return false;
|
||||
var ts=parseInt(xhr.responseText,10);
|
||||
if(isNaN(ts))return false;
|
||||
return(Date.now()-ts)<_heartbeatMaxAge;
|
||||
}catch(e){return false;}
|
||||
}
|
||||
function boot(){
|
||||
if(!checkHeartbeat()){
|
||||
console.log('[AG SDK] Heartbeat missing or stale — extension disabled? Skipping.');
|
||||
return;
|
||||
}
|
||||
if(document.readyState==='complete')setTimeout(start,3000);
|
||||
else window.addEventListener('load',function(){setTimeout(start,3000);});
|
||||
}
|
||||
boot();
|
||||
})();`;
|
||||
}
|
||||
|
||||
private _css(configs: IntegrationConfig[]): string {
|
||||
// Only include CSS for points that are actually used
|
||||
const points = new Set(configs.map(c => c.point));
|
||||
|
||||
// All colors now use _theme variables for light/dark mode support
|
||||
// CSS is generated as a JS template that reads _theme at runtime
|
||||
return `
|
||||
// ─── Theme-Aware CSS ───
|
||||
var _cssRules=[
|
||||
'.${AG_PREFIX}meta{padding:3px 8px;background:'+_theme.metaBg+';border-top:1px solid '+_theme.border+';font-family:"Cascadia Code","Fira Code",monospace;font-size:9px;color:'+_theme.fgDim+';display:flex;align-items:center;gap:5px;flex-wrap:wrap;transition:all .2s;cursor:default;user-select:none;margin-top:2px;border-radius:0 0 6px 6px}',
|
||||
'.${AG_PREFIX}meta:hover{background:'+_theme.metaBgHover+';color:'+_theme.fgHover+'}',
|
||||
'.${AG_PREFIX}t{padding:1px 4px;border-radius:3px;font-size:8px;font-weight:700;letter-spacing:.3px}',
|
||||
'.${AG_PREFIX}u{background:'+_theme.successBg+';color:'+_theme.success+'}',
|
||||
'.${AG_PREFIX}b{background:'+_theme.accentBg+';color:'+_theme.accent+'}',
|
||||
'.${AG_PREFIX}k{color:'+_theme.fgDim+';font-size:8px}',
|
||||
'.${AG_PREFIX}v{color:'+_theme.fg+';font-size:8px;opacity:.55}',
|
||||
'.${AG_PREFIX}hi{color:'+_theme.accent+'}',
|
||||
'.${AG_PREFIX}w{color:'+_theme.warn+'}',
|
||||
'.${AG_PREFIX}s{color:'+_theme.sep+'}',
|
||||
// Toast
|
||||
'.${AG_PREFIX}toast{position:fixed;bottom:80px;right:20px;background:'+_theme.bg+';border:1px solid '+_theme.borderHover+';border-radius:8px;padding:10px 14px;font-family:"Cascadia Code",monospace;font-size:10px;color:'+_theme.fg+';z-index:99999;max-width:320px;backdrop-filter:blur(10px);box-shadow:0 4px 24px '+_theme.shadow+';animation:${AG_PREFIX}fade .25s ease}',
|
||||
'@keyframes ${AG_PREFIX}fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}',
|
||||
'.${AG_PREFIX}toast-t{color:'+_theme.accent+';font-weight:700;margin-bottom:5px;font-size:11px;display:flex;align-items:center;gap:6px}',
|
||||
'.${AG_PREFIX}toast-r{display:flex;gap:8px;margin:1px 0}',
|
||||
'.${AG_PREFIX}toast-k{color:'+_theme.fgDim+';min-width:70px}',
|
||||
'.${AG_PREFIX}toast-v{color:'+_theme.fg+'}',
|
||||
'.${AG_PREFIX}toast-badge{font-size:8px;padding:1px 5px;border-radius:3px;font-weight:700}',
|
||||
// Buttons
|
||||
'.${AG_PREFIX}hdr{display:inline-flex;align-items:center;gap:3px;padding:1px 6px;border-radius:4px;cursor:pointer;color:'+_theme.fgDim+';font-size:9px;font-family:"Cascadia Code",monospace;transition:all .15s;user-select:none}',
|
||||
'.${AG_PREFIX}hdr:hover{background:'+_theme.accentBg+';color:'+_theme.accent+'}',
|
||||
'.${AG_PREFIX}inp{display:inline-flex;align-items:center;justify-content:center;min-width:18px;height:18px;border-radius:4px;cursor:pointer;color:'+_theme.fgDim+';font-size:11px;transition:all .15s;flex-shrink:0;padding:0 4px;font-family:"Cascadia Code",monospace}',
|
||||
'.${AG_PREFIX}inp:hover{background:'+_theme.accentBg+';color:'+_theme.accent+'}',
|
||||
'.${AG_PREFIX}menu{padding:4px 8px;cursor:pointer;font-size:11px;color:'+_theme.fg+';opacity:.7;transition:all .12s;display:flex;align-items:center;gap:6px;white-space:nowrap}',
|
||||
'.${AG_PREFIX}menu:hover{background:'+_theme.accentBg+';color:'+_theme.accent+';opacity:1}',
|
||||
'.${AG_PREFIX}vote{display:inline-flex;align-items:center;gap:3px;padding:1px 6px;border-radius:3px;cursor:pointer;color:'+_theme.fgDim+';font-size:9px;font-family:"Cascadia Code",monospace;transition:all .15s;margin-left:4px}',
|
||||
'.${AG_PREFIX}vote:hover{background:'+_theme.accentBg+';color:'+_theme.accent+'}',
|
||||
'.${AG_PREFIX}ubadge{display:inline-flex;align-items:center;gap:2px;padding:1px 5px;border-radius:3px;background:'+_theme.successBg+';cursor:pointer;color:'+_theme.success+';opacity:.4;font-size:8px;font-family:"Cascadia Code",monospace;transition:all .15s;margin-left:3px}',
|
||||
'.${AG_PREFIX}ubadge:hover{background:'+_theme.successBg+';color:'+_theme.success+';opacity:1}',
|
||||
'.${AG_PREFIX}title-hint{position:absolute;right:0;top:50%;transform:translateY(-50%);font-size:8px;color:'+_theme.accent+';opacity:.3;pointer-events:none;font-family:"Cascadia Code",monospace;transition:opacity .2s}',
|
||||
'.${AG_PREFIX}title-wrap:hover .${AG_PREFIX}title-hint{opacity:1}'
|
||||
];
|
||||
var css=document.createElement('style');
|
||||
css.textContent=_cssRules.join('\\n');
|
||||
document.head.appendChild(css);
|
||||
`;
|
||||
}
|
||||
|
||||
private _helpers(): string {
|
||||
return `
|
||||
function mk(tag,cls,txt){var e=document.createElement(tag);if(cls)e.className=cls;if(txt!==undefined)e.textContent=txt;return e;}
|
||||
function fmt(n){return n>=1000?(n/1000).toFixed(1)+'k':''+n;}
|
||||
`;
|
||||
}
|
||||
|
||||
private _toast(): string {
|
||||
return `
|
||||
var _toastT=0;
|
||||
function toast(title,badge,rows){
|
||||
var old=document.querySelector('.${AG_PREFIX}toast');if(old)old.remove();
|
||||
var t=mk('div','${AG_PREFIX}toast');
|
||||
var hdr=mk('div','${AG_PREFIX}toast-t');
|
||||
hdr.appendChild(document.createTextNode(title));
|
||||
if(badge){var b=mk('span','${AG_PREFIX}toast-badge');b.textContent=badge[0];b.style.background=badge[1];b.style.color=badge[2];hdr.appendChild(b);}
|
||||
t.appendChild(hdr);
|
||||
rows.forEach(function(r){var row=mk('div','${AG_PREFIX}toast-r');row.appendChild(mk('span','${AG_PREFIX}toast-k',r[0]));row.appendChild(mk('span','${AG_PREFIX}toast-v',r[1]));t.appendChild(row);});
|
||||
document.body.appendChild(t);
|
||||
clearTimeout(_toastT);_toastT=setTimeout(function(){if(t.parentNode)t.remove();},6000);
|
||||
t.addEventListener('click',function(){t.remove();});
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _stats(): string {
|
||||
return `
|
||||
function getStats(){
|
||||
var c=document.querySelector(${JSON.stringify(Selectors.TURNS_CONTAINER)});
|
||||
if(!c)return null;
|
||||
var turns=0,uC=0,bC=0,code=0;
|
||||
Array.from(c.children).forEach(function(ch){
|
||||
if(ch.getAttribute('${AG_DATA_ATTR}')||ch.children.length<1)return;
|
||||
turns++;
|
||||
uC+=(ch.children[0]?.textContent?.trim()||'').length;
|
||||
bC+=(ch.children[1]?.textContent?.trim()||'').length;
|
||||
code+=(ch.children[1]?.querySelectorAll('pre')?.length||0);
|
||||
});
|
||||
return{turns:turns,u:uC,b:bC,code:code};
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
// ─── Point generators ─────────────────────────────────────────────
|
||||
|
||||
private _generatePoint(point: IntegrationPoint, configs: IntegrationConfig[]): string {
|
||||
switch (point) {
|
||||
case IntegrationPoint.TOP_BAR:
|
||||
return this._genTopBar(configs as IButtonIntegration[]);
|
||||
case IntegrationPoint.TOP_RIGHT:
|
||||
return this._genTopRight(configs as IButtonIntegration[]);
|
||||
case IntegrationPoint.INPUT_AREA:
|
||||
return this._genInputArea(configs as IButtonIntegration[]);
|
||||
case IntegrationPoint.BOTTOM_ICONS:
|
||||
return this._genBottomIcons(configs as IButtonIntegration[]);
|
||||
case IntegrationPoint.TURN_METADATA:
|
||||
return this._genTurnMeta(configs as ITurnMetaIntegration[]);
|
||||
case IntegrationPoint.USER_BADGE:
|
||||
return this._genUserBadge(configs as IUserBadgeIntegration[]);
|
||||
case IntegrationPoint.BOT_ACTION:
|
||||
return this._genBotAction(configs as IBotActionIntegration[]);
|
||||
case IntegrationPoint.DROPDOWN_MENU:
|
||||
return this._genDropdown(configs as IDropdownIntegration[]);
|
||||
case IntegrationPoint.CHAT_TITLE:
|
||||
return this._genTitle(configs as ITitleIntegration[]);
|
||||
default:
|
||||
return `// Unknown point: ${point}`;
|
||||
}
|
||||
}
|
||||
|
||||
private _genToastCall(toast?: IToastConfig): string {
|
||||
if (!toast) return '';
|
||||
const badge = toast.badge
|
||||
? `[${JSON.stringify(toast.badge.text)},${JSON.stringify(toast.badge.bgColor)},${JSON.stringify(toast.badge.textColor)}]`
|
||||
: 'null';
|
||||
const rows = toast.rows
|
||||
.map(r => {
|
||||
if (r.dynamic) {
|
||||
return `[${JSON.stringify(r.key)},${r.value}]`;
|
||||
}
|
||||
return `[${JSON.stringify(r.key)},${JSON.stringify(r.value)}]`;
|
||||
})
|
||||
.join(',');
|
||||
return `toast(${JSON.stringify(toast.title)},${badge},[${rows}]);`;
|
||||
}
|
||||
|
||||
private _genTopBar(configs: IButtonIntegration[]): string {
|
||||
const buttons = configs.map(c => {
|
||||
const toastCall = this._genToastCall(c.toast);
|
||||
return ` var btn_${c.id}=mk('a','${AG_PREFIX}hdr ${AG_PREFIX}${c.id}');
|
||||
btn_${c.id}.textContent=${JSON.stringify(c.icon)};
|
||||
btn_${c.id}.title=${JSON.stringify(c.tooltip || '')};
|
||||
btn_${c.id}.addEventListener('click',function(){${toastCall}});
|
||||
iconsArea.insertBefore(btn_${c.id},iconsArea.children[1]);`;
|
||||
});
|
||||
|
||||
return `
|
||||
function integrateTopBar(){
|
||||
var p=document.querySelector(${JSON.stringify(Selectors.PANEL)});if(!p)return;
|
||||
var topBar=p.querySelector(${JSON.stringify(Selectors.TOP_BAR)});if(!topBar)return;
|
||||
var iconsArea=topBar.querySelector(${JSON.stringify(Selectors.TOP_ICONS)});
|
||||
if(!iconsArea||iconsArea.querySelector('.${AG_PREFIX}${configs[0].id}'))return;
|
||||
${buttons.join('\n')}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _genTopRight(configs: IButtonIntegration[]): string {
|
||||
const buttons = configs.map(c => {
|
||||
const toastCall = this._genToastCall(c.toast);
|
||||
return ` var btn_${c.id}=mk('a','${AG_PREFIX}hdr ${AG_PREFIX}${c.id}');
|
||||
btn_${c.id}.textContent=${JSON.stringify(c.icon)};
|
||||
btn_${c.id}.title=${JSON.stringify(c.tooltip || '')};
|
||||
btn_${c.id}.addEventListener('click',function(){${toastCall}});
|
||||
iconsArea.insertBefore(btn_${c.id},iconsArea.lastElementChild);`;
|
||||
});
|
||||
|
||||
return `
|
||||
function integrateTopRight(){
|
||||
var p=document.querySelector(${JSON.stringify(Selectors.PANEL)});if(!p)return;
|
||||
var topBar=p.querySelector(${JSON.stringify(Selectors.TOP_BAR)});if(!topBar)return;
|
||||
var iconsArea=topBar.querySelector(${JSON.stringify(Selectors.TOP_ICONS)});
|
||||
if(!iconsArea||iconsArea.querySelector('.${AG_PREFIX}${configs[0].id}'))return;
|
||||
${buttons.join('\n')}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _genInputArea(configs: IButtonIntegration[]): string {
|
||||
const buttons = configs.map(c => {
|
||||
const toastCall = this._genToastCall(c.toast);
|
||||
return ` var btn=mk('div','${AG_PREFIX}inp ${AG_PREFIX}${c.id}');
|
||||
btn.textContent=${JSON.stringify(c.icon)};
|
||||
btn.title=${JSON.stringify(c.tooltip || '')};
|
||||
btn.addEventListener('click',function(){${toastCall}});
|
||||
btnRow.insertBefore(btn,btnRow.firstChild);`;
|
||||
});
|
||||
|
||||
return `
|
||||
function integrateInputArea(){
|
||||
var ib=document.querySelector(${JSON.stringify(Selectors.INPUT_BOX)});
|
||||
if(!ib||ib.querySelector('.${AG_PREFIX}${configs[0].id}'))return;
|
||||
var allBtns=ib.querySelectorAll('button,[role="button"]');
|
||||
if(allBtns.length===0)return;
|
||||
var btnRow=allBtns[allBtns.length-1].parentElement;if(!btnRow)return;
|
||||
${buttons.join('\n')}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _genBottomIcons(configs: IButtonIntegration[]): string {
|
||||
const buttons = configs.map(c => {
|
||||
const toastCall = this._genToastCall(c.toast);
|
||||
return ` var btn=mk('div','${AG_PREFIX}inp ${AG_PREFIX}${c.id}');
|
||||
btn.textContent=${JSON.stringify(c.icon)};
|
||||
btn.title=${JSON.stringify(c.tooltip || '')};
|
||||
btn.addEventListener('click',function(){${toastCall}});
|
||||
row.appendChild(btn);`;
|
||||
});
|
||||
|
||||
return `
|
||||
function integrateBottomIcons(){
|
||||
var ib=document.querySelector(${JSON.stringify(Selectors.INPUT_BOX)});
|
||||
if(!ib||ib.querySelector('.${AG_PREFIX}${configs[0].id}'))return;
|
||||
var rows=ib.querySelectorAll('.flex.items-center');
|
||||
var row=null;
|
||||
for(var i=0;i<rows.length;i++){if(rows[i].querySelectorAll('svg').length>=2){row=rows[i];}}
|
||||
if(!row)return;
|
||||
${buttons.join('\n')}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _genTurnMeta(configs: ITurnMetaIntegration[]): string {
|
||||
// Take first config for metrics (single turn metadata style)
|
||||
const cfg = configs[0];
|
||||
const metricParts: string[] = [];
|
||||
|
||||
for (const m of cfg.metrics) {
|
||||
switch (m) {
|
||||
case 'turnNumber':
|
||||
metricParts.push(`meta.appendChild(mk('span','${AG_PREFIX}t ${AG_PREFIX}b','T'+tI));`);
|
||||
break;
|
||||
case 'userCharCount':
|
||||
metricParts.push(`if(uL>0){meta.appendChild(mk('span','${AG_PREFIX}t ${AG_PREFIX}u','USER'));meta.appendChild(mk('span','${AG_PREFIX}k',fmt(uL)));}`);
|
||||
break;
|
||||
case 'separator':
|
||||
metricParts.push(`if(uL>0&&bL>0)meta.appendChild(mk('span','${AG_PREFIX}s','\\u2502'));`);
|
||||
break;
|
||||
case 'aiCharCount':
|
||||
metricParts.push(`if(bL>0){meta.appendChild(mk('span','${AG_PREFIX}t ${AG_PREFIX}b','AI'));meta.appendChild(mk('span','${AG_PREFIX}k',fmt(bL)));}`);
|
||||
break;
|
||||
case 'codeBlocks':
|
||||
metricParts.push(`if(codes>0){meta.appendChild(mk('span','${AG_PREFIX}k','code:'));meta.appendChild(mk('span','${AG_PREFIX}v ${AG_PREFIX}w',''+codes));}`);
|
||||
break;
|
||||
case 'thinkingIndicator':
|
||||
metricParts.push(`if(brain)meta.appendChild(mk('span','${AG_PREFIX}v','\\u{1F9E0}'));`);
|
||||
break;
|
||||
case 'ratio':
|
||||
metricParts.push(`if(uL>0&&bL>0){meta.appendChild(mk('span','${AG_PREFIX}k',(bL/uL).toFixed(1)+'x'));}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const clickHandler = cfg.clickable !== false
|
||||
? `meta.addEventListener('click',function(){toast('Turn '+tI,null,[['user:',fmt(uL)],['AI:',fmt(bL)],['ratio:',uL>0?(bL/uL).toFixed(1)+'x':'\\u2014']]);});`
|
||||
: '';
|
||||
|
||||
return `
|
||||
function integrateTurnMeta(){
|
||||
var c=document.querySelector(${JSON.stringify(Selectors.TURNS_CONTAINER)});if(!c)return;
|
||||
var tI=0;
|
||||
Array.from(c.children).forEach(function(turn){
|
||||
if(turn.getAttribute('${AG_DATA_ATTR}')||turn.children.length<1)return;
|
||||
turn.setAttribute('${AG_DATA_ATTR}','1');
|
||||
tI++;var uL=(turn.children[0]?.textContent?.trim()||'').length;
|
||||
var bL=(turn.children[1]?.textContent?.trim()||'').length;
|
||||
if(uL===0&&bL===0)return;
|
||||
var codes=turn.children[1]?.querySelectorAll('pre')?.length||0;
|
||||
var brain=(turn.children[1]?.textContent||'').includes('Thought');
|
||||
var meta=mk('div','${AG_PREFIX}meta');
|
||||
${metricParts.join('\n ')}
|
||||
${clickHandler}
|
||||
turn.appendChild(meta);
|
||||
});
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _genUserBadge(configs: IUserBadgeIntegration[]): string {
|
||||
const cfg = configs[0];
|
||||
let displayExpr = 'fmt(uLen)+" ch"';
|
||||
if (cfg.display === 'wordCount') {
|
||||
displayExpr = '(txt.split(/\\\\s+/).length)+" w"';
|
||||
} else if (cfg.display === 'custom' && cfg.customFormat) {
|
||||
displayExpr = cfg.customFormat;
|
||||
}
|
||||
|
||||
return `
|
||||
function integrateUserBadges(){
|
||||
var c=document.querySelector(${JSON.stringify(Selectors.TURNS_CONTAINER)});if(!c)return;
|
||||
Array.from(c.children).forEach(function(turn,i){
|
||||
if(turn.getAttribute('${AG_DATA_ATTR}u')||turn.children.length<1)return;
|
||||
var bubble=turn.children[0]?.querySelector(${JSON.stringify(Selectors.USER_BUBBLE)});
|
||||
if(!bubble)return;
|
||||
var txt=turn.children[0]?.textContent?.trim()||'';
|
||||
var uLen=txt.length;if(uLen<5)return;
|
||||
turn.setAttribute('${AG_DATA_ATTR}u','1');
|
||||
var row=turn.children[0]?.querySelector('.flex.w-full,.flex.flex-row')||turn.children[0];
|
||||
var badge=mk('span','${AG_PREFIX}ubadge');
|
||||
badge.textContent=${displayExpr};
|
||||
badge.title='SDK: User message';
|
||||
row.appendChild(badge);
|
||||
});
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _genBotAction(configs: IBotActionIntegration[]): string {
|
||||
const items = configs.map(c => {
|
||||
const toastCall = this._genToastCall(c.toast);
|
||||
return `var b=mk('span','${AG_PREFIX}vote');b.textContent=${JSON.stringify(c.icon + ' ' + c.label)};
|
||||
b.addEventListener('click',function(ev){ev.stopPropagation();${toastCall}});
|
||||
row.appendChild(b);`;
|
||||
});
|
||||
|
||||
return `
|
||||
function integrateBotAction(){
|
||||
var c=document.querySelector(${JSON.stringify(Selectors.TURNS_CONTAINER)});if(!c)return;
|
||||
c.querySelectorAll('span,button,a,div').forEach(function(el){
|
||||
if(el.getAttribute('${AG_DATA_ATTR}v'))return;
|
||||
var txt=el.textContent?.trim();
|
||||
if(txt==='Good'||txt==='Bad'){
|
||||
var row=el.parentElement;if(!row||row.querySelector('.${AG_PREFIX}vote'))return;
|
||||
el.setAttribute('${AG_DATA_ATTR}v','1');
|
||||
${items.join('\n ')}
|
||||
}
|
||||
});
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _genDropdown(configs: IDropdownIntegration[]): string {
|
||||
const markers = JSON.stringify(Selectors.DROPDOWN_MARKER_TEXT);
|
||||
const items = configs.map(c => {
|
||||
const toastCall = this._genToastCall(c.toast);
|
||||
const sep = c.separator
|
||||
? `var sep=mk('div','');sep.style.cssText='height:1px;background:rgba(255,255,255,.06);margin:4px 8px';dd.appendChild(sep);`
|
||||
: '';
|
||||
return `${sep}
|
||||
var mi=mk('div','${AG_PREFIX}menu');
|
||||
${c.icon ? `mi.appendChild(mk('span','',${JSON.stringify(c.icon)}));` : ''}
|
||||
mi.appendChild(document.createTextNode(${JSON.stringify(c.label)}));
|
||||
mi.addEventListener('click',function(){${toastCall}});
|
||||
dd.appendChild(mi);`;
|
||||
});
|
||||
|
||||
return `
|
||||
function integrateDropdown(){
|
||||
var dds=document.querySelectorAll('.rounded-bg.py-1,.rounded-lg.py-1');
|
||||
dds.forEach(function(dd){
|
||||
if(dd.getAttribute('${AG_DATA_ATTR}m'))return;
|
||||
var items=dd.querySelectorAll(${JSON.stringify(Selectors.DROPDOWN_ITEM)});
|
||||
var markers=${markers};
|
||||
var found=false;
|
||||
items.forEach(function(it){markers.forEach(function(m){if((it.textContent||'').includes(m))found=true;});});
|
||||
if(!found)return;
|
||||
dd.setAttribute('${AG_DATA_ATTR}m','1');
|
||||
${items.join('\n ')}
|
||||
});
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _genTitle(configs: ITitleIntegration[]): string {
|
||||
const cfg = configs[0];
|
||||
const toastCall = this._genToastCall(cfg.toast);
|
||||
const event = cfg.interaction || 'dblclick';
|
||||
|
||||
return `
|
||||
function integrateTitle(){
|
||||
var p=document.querySelector(${JSON.stringify(Selectors.PANEL)});if(!p)return;
|
||||
var el=p.querySelector(${JSON.stringify(Selectors.TITLE)});
|
||||
if(!el||el.getAttribute('${AG_DATA_ATTR}t'))return;
|
||||
el.setAttribute('${AG_DATA_ATTR}t','1');
|
||||
el.style.cursor='pointer';
|
||||
el.classList.add('${AG_PREFIX}title-wrap');
|
||||
el.style.position='relative';
|
||||
${cfg.hint ? `var hint=mk('span','${AG_PREFIX}title-hint',${JSON.stringify(cfg.hint)});el.appendChild(hint);` : ''}
|
||||
el.addEventListener(${JSON.stringify(event)},function(){
|
||||
var title=el.textContent?.replace(${JSON.stringify(cfg.hint || '')},'')?.trim()||'';
|
||||
${toastCall || `toast('Chat',null,[['title:',title],['chars:',''+title.length]]);`}
|
||||
});
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
// ─── Main loop ────────────────────────────────────────────────────
|
||||
|
||||
private _mainLoop(points: IntegrationPoint[]): string {
|
||||
const fnMap: Record<string, string> = {
|
||||
[IntegrationPoint.TOP_BAR]: 'integrateTopBar',
|
||||
[IntegrationPoint.TOP_RIGHT]: 'integrateTopRight',
|
||||
[IntegrationPoint.INPUT_AREA]: 'integrateInputArea',
|
||||
[IntegrationPoint.BOTTOM_ICONS]: 'integrateBottomIcons',
|
||||
[IntegrationPoint.TURN_METADATA]: 'integrateTurnMeta',
|
||||
[IntegrationPoint.USER_BADGE]: 'integrateUserBadges',
|
||||
[IntegrationPoint.BOT_ACTION]: 'integrateBotAction',
|
||||
[IntegrationPoint.DROPDOWN_MENU]: 'integrateDropdown',
|
||||
[IntegrationPoint.CHAT_TITLE]: 'integrateTitle',
|
||||
};
|
||||
|
||||
const calls = points.map(p => ` ${fnMap[p]}();`).join('\n');
|
||||
|
||||
return `
|
||||
function fullScan(){
|
||||
${calls}
|
||||
}
|
||||
var _timer=0;
|
||||
function debounced(){clearTimeout(_timer);_timer=setTimeout(function(){requestAnimationFrame(fullScan);},400);}
|
||||
function start(){
|
||||
var p=document.querySelector(${JSON.stringify(Selectors.PANEL)});
|
||||
if(!p){setTimeout(start,1000);return;}
|
||||
fullScan();
|
||||
new MutationObserver(debounced).observe(p,{childList:true,subtree:true});
|
||||
setInterval(fullScan,8000);
|
||||
console.log('[AG SDK] Active \\u2014 ${points.length} integration points');
|
||||
}
|
||||
`;
|
||||
}
|
||||
}
|
||||
56
antigravity-sdk-main/src/integration/selectors.ts
Normal file
56
antigravity-sdk-main/src/integration/selectors.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* DOM Selectors — Single source of truth for all Agent View selectors.
|
||||
*
|
||||
* Verified against Antigravity v1.107.0 DOM (2026-02-28).
|
||||
* If Antigravity updates break selectors, only THIS file needs updating.
|
||||
*
|
||||
* @module integration/selectors
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
|
||||
export const Selectors = {
|
||||
/** The entire agent side panel container */
|
||||
PANEL: '.antigravity-agent-side-panel',
|
||||
|
||||
/** Top bar with title and action icons */
|
||||
TOP_BAR: '.flex.items-center.justify-between',
|
||||
|
||||
/** Icons area in top bar (contains +, refresh, ..., X) */
|
||||
TOP_ICONS: '.flex.items-center.gap-2',
|
||||
|
||||
/** Chat title element */
|
||||
TITLE: '.flex.min-w-0.items-center.overflow-hidden',
|
||||
|
||||
/** Main conversation scroll area */
|
||||
CONVERSATION: '#conversation',
|
||||
|
||||
/** Message turns container (direct children are turns) */
|
||||
TURNS_CONTAINER: '#conversation .gap-y-3',
|
||||
|
||||
/** User message bubble (inside turn) */
|
||||
USER_BUBBLE: '.rounded-lg',
|
||||
|
||||
/** Input box container */
|
||||
INPUT_BOX: '#antigravity\\.agentSidePanelInputBox',
|
||||
|
||||
/** 3-dot dropdown menu (appears dynamically) */
|
||||
DROPDOWN_MARKER_TEXT: ['Customization', 'Export'],
|
||||
|
||||
/** Dropdown menu item class pattern */
|
||||
DROPDOWN_ITEM: '.cursor-pointer',
|
||||
|
||||
/** Good/Bad feedback text markers */
|
||||
FEEDBACK_MARKERS: ['Good', 'Bad'],
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* CSS class prefixes used by SDK integrations.
|
||||
* Used to identify and clean up integrated elements.
|
||||
*/
|
||||
export const AG_PREFIX = 'ag-';
|
||||
|
||||
/**
|
||||
* Data attribute used to mark processed elements.
|
||||
*/
|
||||
export const AG_DATA_ATTR = 'data-ag-sdk';
|
||||
171
antigravity-sdk-main/src/integration/title-manager.ts
Normal file
171
antigravity-sdk-main/src/integration/title-manager.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* Title Manager — Extension-host API for managing chat titles.
|
||||
*
|
||||
* Allows extensions to programmatically rename conversations
|
||||
* by writing to a data file that the renderer-side title proxy reads.
|
||||
*
|
||||
* Also provides a direct localStorage synchronization mechanism
|
||||
* via the integration script's window.__agSDKTitles API.
|
||||
*
|
||||
* @module integration/title-manager
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const sdk = new AntigravitySDK(context);
|
||||
* await sdk.initialize();
|
||||
*
|
||||
* // Rename via extension host (writes data file, renderer picks up on next poll)
|
||||
* sdk.titles.rename('cascade-uuid', 'My Custom Title');
|
||||
*
|
||||
* // Get all custom titles
|
||||
* const titles = sdk.titles.getAll();
|
||||
*
|
||||
* // Remove a custom title (reverts to auto-generated summary)
|
||||
* sdk.titles.remove('cascade-uuid');
|
||||
* ```
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { Logger } from '../core/logger';
|
||||
import { IDisposable } from '../core/disposable';
|
||||
import { getTitlesDataFile } from './title-proxy';
|
||||
|
||||
const log = new Logger('TitleManager');
|
||||
|
||||
/**
|
||||
* Manages custom conversation titles from the extension host.
|
||||
*
|
||||
* Titles are persisted in a JSON file in the workbench directory.
|
||||
* The renderer-side title proxy reads this file and merges with localStorage.
|
||||
*/
|
||||
export class TitleManager implements IDisposable {
|
||||
private _titles: Record<string, string> = {};
|
||||
private _dataPath: string = '';
|
||||
private _initialized = false;
|
||||
|
||||
/**
|
||||
* Initialize with the workbench directory path.
|
||||
*
|
||||
* @param workbenchDir - Path to workbench directory where data file is stored
|
||||
* @param namespace - Extension namespace for file isolation
|
||||
*/
|
||||
initialize(workbenchDir: string, namespace: string = 'default'): void {
|
||||
this._dataPath = path.join(workbenchDir, getTitlesDataFile(namespace));
|
||||
this._load();
|
||||
this._initialized = true;
|
||||
log.info(`Initialized, ${Object.keys(this._titles).length} custom titles loaded`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the manager is initialized.
|
||||
*/
|
||||
get isInitialized(): boolean {
|
||||
return this._initialized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a custom title for a conversation.
|
||||
*
|
||||
* The title will be displayed in the Agent View title bar
|
||||
* and conversation list instead of the auto-generated summary.
|
||||
*
|
||||
* @param cascadeId - The conversation's cascade ID (UUID)
|
||||
* @param title - The custom title to display
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Rename the active conversation
|
||||
* const id = sdk.titles.getActiveCascadeId();
|
||||
* sdk.titles.rename(id, 'Project Alpha Discussion');
|
||||
* ```
|
||||
*/
|
||||
rename(cascadeId: string, title: string): void {
|
||||
if (!cascadeId) {
|
||||
log.warn('rename: cascadeId is required');
|
||||
return;
|
||||
}
|
||||
if (!title || !title.trim()) {
|
||||
log.warn('rename: title cannot be empty');
|
||||
return;
|
||||
}
|
||||
this._titles[cascadeId] = title.trim();
|
||||
this._save();
|
||||
log.debug(`Renamed ${cascadeId.substring(0, 8)}... -> "${title.trim()}"`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the custom title for a conversation.
|
||||
*
|
||||
* @param cascadeId - The conversation's cascade ID
|
||||
* @returns The custom title, or undefined if no custom title is set
|
||||
*/
|
||||
getTitle(cascadeId: string): string | undefined {
|
||||
return this._titles[cascadeId];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all custom titles.
|
||||
*
|
||||
* @returns A copy of the titles map (cascadeId -> title)
|
||||
*/
|
||||
getAll(): Readonly<Record<string, string>> {
|
||||
return { ...this._titles };
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a custom title, reverting to the auto-generated summary.
|
||||
*
|
||||
* @param cascadeId - The conversation's cascade ID
|
||||
*/
|
||||
remove(cascadeId: string): void {
|
||||
if (this._titles[cascadeId]) {
|
||||
delete this._titles[cascadeId];
|
||||
this._save();
|
||||
log.debug(`Removed title for ${cascadeId.substring(0, 8)}...`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all custom titles.
|
||||
*/
|
||||
clear(): void {
|
||||
this._titles = {};
|
||||
this._save();
|
||||
log.debug('Cleared all custom titles');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of custom titles.
|
||||
*/
|
||||
get count(): number {
|
||||
return Object.keys(this._titles).length;
|
||||
}
|
||||
|
||||
/** Load titles from the data file */
|
||||
private _load(): void {
|
||||
try {
|
||||
if (fs.existsSync(this._dataPath)) {
|
||||
const content = fs.readFileSync(this._dataPath, 'utf8');
|
||||
this._titles = JSON.parse(content) || {};
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn(`Failed to load titles: ${err}`);
|
||||
this._titles = {};
|
||||
}
|
||||
}
|
||||
|
||||
/** Save titles to the data file */
|
||||
private _save(): void {
|
||||
if (!this._dataPath) return;
|
||||
try {
|
||||
fs.writeFileSync(this._dataPath, JSON.stringify(this._titles, null, 2), 'utf8');
|
||||
} catch (err) {
|
||||
log.warn(`Failed to save titles: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
// Nothing to clean up - titles persist on disk
|
||||
}
|
||||
}
|
||||
292
antigravity-sdk-main/src/integration/title-proxy.ts
Normal file
292
antigravity-sdk-main/src/integration/title-proxy.ts
Normal file
@@ -0,0 +1,292 @@
|
||||
/**
|
||||
* Title Proxy — Renderer-side code for intercepting chat summaries.
|
||||
*
|
||||
* Generates JavaScript that runs in the workbench renderer process.
|
||||
* Uses Preact VNode context walk to find the summaries provider,
|
||||
* wraps getState() to inject custom titles from localStorage,
|
||||
* and captures onDidChange listeners for forced re-renders.
|
||||
*
|
||||
* All identifiers used here are STRUCTURALLY MATCHED, not hardcoded
|
||||
* minified variable names — this survives obfuscation changes.
|
||||
*
|
||||
* @module integration/title-proxy
|
||||
* @internal
|
||||
*/
|
||||
|
||||
/** localStorage key prefix for custom titles */
|
||||
const TITLES_STORAGE_PREFIX = 'ag-sdk-titles';
|
||||
|
||||
/** Data file prefix for extension-host to set titles */
|
||||
const TITLES_DATA_PREFIX = 'ag-sdk-titles';
|
||||
|
||||
/**
|
||||
* Generate the renderer-side title proxy JavaScript.
|
||||
*
|
||||
* This code:
|
||||
* 1. BFS walks the Preact VNode tree (limit 3000, arrays not counted)
|
||||
* 2. Finds summaries provider via structural matching
|
||||
* 3. Wraps provider.getState() to inject custom titles
|
||||
* 4. Captures onDidChange listeners for forced re-renders
|
||||
* 5. Reads custom titles from localStorage + data file
|
||||
* 6. Exposes window.__agSDKTitles API for inline rename
|
||||
*
|
||||
* @param dataFilePath - Relative path to the JSON data file (for extension-host titles)
|
||||
* @returns JavaScript source code
|
||||
*/
|
||||
export function generateTitleProxyCode(namespace: string = 'default'): string {
|
||||
const slug = namespace.replace(/[^a-zA-Z0-9-]/g, '-');
|
||||
const storageKey = `${TITLES_STORAGE_PREFIX}-${slug}`;
|
||||
const dataFile = `./${TITLES_DATA_PREFIX}-${slug}.json`;
|
||||
return `
|
||||
// ── AG SDK: Title Proxy ──────────────────────────────────────────
|
||||
// Intercepts summaries provider to inject custom chat titles.
|
||||
// Uses structural matching (obfuscation-safe).
|
||||
|
||||
(function initTitleProxy(){
|
||||
var PANEL_SEL='.antigravity-agent-side-panel';
|
||||
var TITLE_SEL='.flex.min-w-0.items-center.overflow-hidden';
|
||||
var STORAGE_KEY='${storageKey}';
|
||||
var DATA_FILE='${dataFile}';
|
||||
|
||||
var _provider=null;
|
||||
var _origGetState=null;
|
||||
var _listeners=[];
|
||||
var _customTitles={};
|
||||
var _searchTime=0;
|
||||
|
||||
// ── Load / Save ────────────────────────────────────────────────
|
||||
|
||||
function loadTitles(){
|
||||
// Step 1: Load from localStorage (sync, fast)
|
||||
try{_customTitles=JSON.parse(localStorage.getItem(STORAGE_KEY)||'{}');}catch(e){_customTitles={};}
|
||||
// Step 2: Merge extension-host titles from data file (async fetch)
|
||||
fetch(DATA_FILE).then(function(r){
|
||||
if(!r.ok)return;
|
||||
return r.text();
|
||||
}).then(function(text){
|
||||
if(!text)return;
|
||||
try{
|
||||
var extTitles=JSON.parse(text);
|
||||
if(extTitles&&typeof extTitles==='object'){
|
||||
for(var k in extTitles){_customTitles[k]=extTitles[k];}
|
||||
saveTitles();
|
||||
notifyListeners();
|
||||
}
|
||||
}catch(e){}
|
||||
}).catch(function(){});
|
||||
}
|
||||
|
||||
function saveTitles(){
|
||||
try{localStorage.setItem(STORAGE_KEY,JSON.stringify(_customTitles));}catch(e){}
|
||||
}
|
||||
|
||||
// ── Notify ─────────────────────────────────────────────────────
|
||||
|
||||
function notifyListeners(){
|
||||
for(var i=0;i<_listeners.length;i++){try{_listeners[i]();}catch(e){}}
|
||||
}
|
||||
|
||||
// ── Provider Wrapping ──────────────────────────────────────────
|
||||
|
||||
function wrapProvider(provider){
|
||||
if(provider.__agSDKWrapped)return;
|
||||
provider.__agSDKWrapped=true;
|
||||
_provider=provider;
|
||||
var origFn=provider.getState;
|
||||
_origGetState=origFn;
|
||||
|
||||
// Wrap getState to inject custom titles
|
||||
provider.getState=function(){
|
||||
var state=origFn.call(provider);
|
||||
if(!state||!state.summaries)return state;
|
||||
var hasOverrides=false;
|
||||
for(var cid in _customTitles){if(state.summaries[cid]){hasOverrides=true;break;}}
|
||||
if(!hasOverrides)return state;
|
||||
var ns={};
|
||||
for(var k in state.summaries)ns[k]=state.summaries[k];
|
||||
for(var cid in _customTitles){
|
||||
if(ns[cid]){
|
||||
var copy={};for(var p in ns[cid])copy[p]=ns[cid][p];
|
||||
copy.summary=_customTitles[cid];
|
||||
ns[cid]=copy;
|
||||
}
|
||||
}
|
||||
var newState={};for(var sk in state)newState[sk]=state[sk];
|
||||
newState.summaries=ns;
|
||||
return newState;
|
||||
};
|
||||
|
||||
// Intercept onDidChange to capture listeners
|
||||
var origOnDidChange=provider.onDidChange;
|
||||
provider.onDidChange=function(callback){
|
||||
_listeners.push(callback);
|
||||
var origDispose=origOnDidChange.call(this,callback);
|
||||
return{dispose:function(){
|
||||
var idx=_listeners.indexOf(callback);
|
||||
if(idx>=0)_listeners.splice(idx,1);
|
||||
origDispose.dispose();
|
||||
}};
|
||||
};
|
||||
|
||||
console.log('[AG SDK] Title proxy active, custom titles:', Object.keys(_customTitles).length);
|
||||
|
||||
// Force re-render so custom titles appear immediately
|
||||
// (without waiting for next native summaries update)
|
||||
setTimeout(function(){notifyListeners();},50);
|
||||
}
|
||||
|
||||
// ── VNode BFS Walk ─────────────────────────────────────────────
|
||||
|
||||
function findProvider(){
|
||||
if(_provider)return;
|
||||
var panel=document.querySelector(PANEL_SEL);
|
||||
if(!panel||!panel.__k)return;
|
||||
// Throttle only AFTER confirming panel exists (don't block retries when panel isn't mounted)
|
||||
var now=Date.now();
|
||||
if(_searchTime&&now-_searchTime<30000)return;
|
||||
_searchTime=now;
|
||||
var queue=[panel.__k],visited=0;
|
||||
while(queue.length>0&&visited<3000){
|
||||
var node=queue.shift();
|
||||
if(!node)continue;
|
||||
if(Array.isArray(node)){
|
||||
for(var ai=0;ai<node.length;ai++){if(node[ai])queue.push(node[ai]);}
|
||||
continue;
|
||||
}
|
||||
visited++;
|
||||
var comp=node.__c;
|
||||
if(comp&&comp.context&&typeof comp.context==='object'){
|
||||
for(var key in comp.context){
|
||||
try{
|
||||
var ctx=comp.context[key];
|
||||
if(!ctx||!ctx.props||!ctx.props.value)continue;
|
||||
var val=ctx.props.value;
|
||||
// Structural match: {provider: {getState() -> {summaries}}}
|
||||
if(val.provider&&typeof val.provider.getState==='function'){
|
||||
var ts=val.provider.getState();
|
||||
if(ts&&ts.summaries){wrapProvider(val.provider);return;}
|
||||
}
|
||||
// Structural match: {trajectorySummariesProvider: {getState() -> {summaries}}}
|
||||
if(val.trajectorySummariesProvider&&typeof val.trajectorySummariesProvider.getState==='function'){
|
||||
var ts2=val.trajectorySummariesProvider.getState();
|
||||
if(ts2&&ts2.summaries){wrapProvider(val.trajectorySummariesProvider);return;}
|
||||
}
|
||||
}catch(e){}
|
||||
}
|
||||
}
|
||||
// Direct props match
|
||||
if(comp&&comp.props&&comp.props.trajectorySummariesProvider){
|
||||
var tsp=comp.props.trajectorySummariesProvider;
|
||||
if(typeof tsp.getState==='function'){
|
||||
try{var ts3=tsp.getState();
|
||||
if(ts3&&ts3.summaries){wrapProvider(tsp);return;}
|
||||
}catch(e){}
|
||||
}
|
||||
}
|
||||
if(node.__k){
|
||||
if(Array.isArray(node.__k)){for(var ki=0;ki<node.__k.length;ki++){if(node.__k[ki])queue.push(node.__k[ki]);}}
|
||||
else{queue.push(node.__k);}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── CascadeId Resolution ───────────────────────────────────────
|
||||
|
||||
function findCascadeIdByTitle(text){
|
||||
if(!_origGetState)return '';
|
||||
try{
|
||||
var state=_origGetState.call(_provider);
|
||||
if(!state||!state.summaries)return '';
|
||||
// Reverse lookup custom titles first
|
||||
for(var cid in _customTitles){if(_customTitles[cid]===text)return cid;}
|
||||
// Match original summaries
|
||||
var bestId='',bestTime=0;
|
||||
for(var cid in state.summaries){
|
||||
var e=state.summaries[cid];
|
||||
if(e&&e.summary===text){
|
||||
var t=0;try{t=new Date(e.lastModifiedTime).getTime();}catch(e){}
|
||||
if(!bestId||t>bestTime){bestId=cid;bestTime=t;}
|
||||
}
|
||||
}
|
||||
return bestId;
|
||||
}catch(e){return '';}
|
||||
}
|
||||
|
||||
// ── Public API ─────────────────────────────────────────────────
|
||||
|
||||
window.__agSDKTitles={
|
||||
rename:function(cascadeId,title){
|
||||
if(!cascadeId||!title)return false;
|
||||
_customTitles[cascadeId]=title;
|
||||
saveTitles();
|
||||
notifyListeners();
|
||||
return true;
|
||||
},
|
||||
renameByCurrentTitle:function(currentTitle,newTitle){
|
||||
var cid=findCascadeIdByTitle(currentTitle);
|
||||
if(!cid)return false;
|
||||
return this.rename(cid,newTitle);
|
||||
},
|
||||
remove:function(cascadeId){
|
||||
delete _customTitles[cascadeId];
|
||||
saveTitles();
|
||||
notifyListeners();
|
||||
},
|
||||
getTitle:function(cascadeId){return _customTitles[cascadeId]||null;},
|
||||
getAll:function(){var copy={};for(var k in _customTitles)copy[k]=_customTitles[k];return copy;},
|
||||
getActiveCascadeId:function(){
|
||||
var panel=document.querySelector(PANEL_SEL);
|
||||
if(!panel)return '';
|
||||
var titleEl=panel.querySelector(TITLE_SEL);
|
||||
if(!titleEl)return '';
|
||||
var text='';
|
||||
function findText(el){
|
||||
for(var i=0;i<el.childNodes.length;i++){
|
||||
var n=el.childNodes[i];
|
||||
if(n.nodeType===3&&n.textContent.trim().length>0)return n.textContent.trim();
|
||||
if(n.nodeType===1){var found=findText(n);if(found)return found;}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
text=findText(titleEl);
|
||||
return text?findCascadeIdByTitle(text):'';
|
||||
},
|
||||
isReady:function(){return !!_provider;},
|
||||
reload:function(){loadTitles();notifyListeners();}
|
||||
};
|
||||
|
||||
// ── Init ───────────────────────────────────────────────────────
|
||||
|
||||
loadTitles();
|
||||
|
||||
function poll(){
|
||||
findProvider();
|
||||
}
|
||||
|
||||
// Poll until provider found, then every 30s for recovery
|
||||
var pollTimer=setInterval(function(){poll();},2000);
|
||||
|
||||
// Initial attempt after DOM is ready
|
||||
if(document.querySelector(PANEL_SEL)){
|
||||
poll();
|
||||
}
|
||||
|
||||
})();
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the data file name for extension-host titles.
|
||||
*/
|
||||
export function getTitlesDataFile(namespace: string = 'default'): string {
|
||||
const slug = namespace.replace(/[^a-zA-Z0-9-]/g, '-');
|
||||
return `${TITLES_DATA_PREFIX}-${slug}.json`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the localStorage key used by the renderer.
|
||||
*/
|
||||
export function getTitlesStorageKey(namespace: string = 'default'): string {
|
||||
const slug = namespace.replace(/[^a-zA-Z0-9-]/g, '-');
|
||||
return `${TITLES_STORAGE_PREFIX}-${slug}`;
|
||||
}
|
||||
213
antigravity-sdk-main/src/integration/types.ts
Normal file
213
antigravity-sdk-main/src/integration/types.ts
Normal file
@@ -0,0 +1,213 @@
|
||||
/**
|
||||
* Integration module types — standardized UI integration points
|
||||
* for the Antigravity Agent View.
|
||||
*
|
||||
* @module integration/types
|
||||
*/
|
||||
|
||||
// ─── Integration Points ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Standardized integration points in the Agent View UI.
|
||||
*
|
||||
* Each point corresponds to a specific DOM location in the
|
||||
* Antigravity chat interface (verified 2026-02-28).
|
||||
*/
|
||||
export enum IntegrationPoint {
|
||||
/** Top bar — next to +, refresh, ... icons */
|
||||
TOP_BAR = 'topBar',
|
||||
/** Top right corner — before the X (close) button */
|
||||
TOP_RIGHT = 'topRight',
|
||||
/** Input area — next to voice/send buttons */
|
||||
INPUT_AREA = 'inputArea',
|
||||
/** Bottom icon row — file, terminal, artifact, chrome icons */
|
||||
BOTTOM_ICONS = 'bottomIcons',
|
||||
/** Per-turn metadata — appended inside each conversation turn */
|
||||
TURN_METADATA = 'turnMeta',
|
||||
/** User message badge — small badge inside user message bubbles */
|
||||
USER_BADGE = 'userBadge',
|
||||
/** Bot response action — button next to Good/Bad feedback */
|
||||
BOT_ACTION = 'botAction',
|
||||
/** 3-dot dropdown menu — extra items in the overflow menu */
|
||||
DROPDOWN_MENU = 'dropdownMenu',
|
||||
/** Chat title bar — interaction on conversation title */
|
||||
CHAT_TITLE = 'chatTitle',
|
||||
}
|
||||
|
||||
// ─── Configuration Interfaces ──────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Base configuration for all integration points.
|
||||
*/
|
||||
export interface IIntegrationBase {
|
||||
/** Unique ID for this integration (prevents duplicates) */
|
||||
id: string;
|
||||
/** Which integration point to target */
|
||||
point: IntegrationPoint;
|
||||
/** Whether this integration is enabled (default: true) */
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for button-type integrations (top bar, input area, etc.).
|
||||
*/
|
||||
export interface IButtonIntegration extends IIntegrationBase {
|
||||
point:
|
||||
| IntegrationPoint.TOP_BAR
|
||||
| IntegrationPoint.TOP_RIGHT
|
||||
| IntegrationPoint.INPUT_AREA
|
||||
| IntegrationPoint.BOTTOM_ICONS;
|
||||
/** Icon (emoji or text glyph) */
|
||||
icon: string;
|
||||
/** Tooltip text */
|
||||
tooltip?: string;
|
||||
/** Toast to show on click */
|
||||
toast?: IToastConfig;
|
||||
/** CSS class override */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for turn-level metadata integration.
|
||||
*/
|
||||
export interface ITurnMetaIntegration extends IIntegrationBase {
|
||||
point: IntegrationPoint.TURN_METADATA;
|
||||
/** Which metrics to display */
|
||||
metrics: TurnMetric[];
|
||||
/** Whether turns are clickable to show details toast */
|
||||
clickable?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for user message badges.
|
||||
*/
|
||||
export interface IUserBadgeIntegration extends IIntegrationBase {
|
||||
point: IntegrationPoint.USER_BADGE;
|
||||
/** What to show in the badge */
|
||||
display: 'charCount' | 'wordCount' | 'custom';
|
||||
/** Custom formatter function body (receives `textLength` as arg) */
|
||||
customFormat?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for bot response action buttons.
|
||||
*/
|
||||
export interface IBotActionIntegration extends IIntegrationBase {
|
||||
point: IntegrationPoint.BOT_ACTION;
|
||||
/** Icon */
|
||||
icon: string;
|
||||
/** Label text */
|
||||
label: string;
|
||||
/** Toast config on click */
|
||||
toast?: IToastConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for dropdown menu items.
|
||||
*/
|
||||
export interface IDropdownIntegration extends IIntegrationBase {
|
||||
point: IntegrationPoint.DROPDOWN_MENU;
|
||||
/** Menu item icon */
|
||||
icon?: string;
|
||||
/** Menu item label */
|
||||
label: string;
|
||||
/** Add separator before this item */
|
||||
separator?: boolean;
|
||||
/** Toast config on click */
|
||||
toast?: IToastConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for chat title interaction.
|
||||
*/
|
||||
export interface ITitleIntegration extends IIntegrationBase {
|
||||
point: IntegrationPoint.CHAT_TITLE;
|
||||
/** Interaction type */
|
||||
interaction: 'click' | 'dblclick' | 'hover';
|
||||
/** Hint text shown on hover */
|
||||
hint?: string;
|
||||
/** Toast config on interaction */
|
||||
toast?: IToastConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Toast popup configuration.
|
||||
*/
|
||||
export interface IToastConfig {
|
||||
/** Toast title */
|
||||
title: string;
|
||||
/** Badge label and colors */
|
||||
badge?: {
|
||||
text: string;
|
||||
bgColor: string;
|
||||
textColor: string;
|
||||
};
|
||||
/** Key-value rows to display */
|
||||
rows: IToastRow[];
|
||||
/** Auto-dismiss after N milliseconds (default: 6000) */
|
||||
duration?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A row in a toast popup.
|
||||
*/
|
||||
export interface IToastRow {
|
||||
/** Label (left side) */
|
||||
key: string;
|
||||
/**
|
||||
* Value (right side).
|
||||
* Can be a static string or a dynamic expression.
|
||||
* Dynamic expressions are JS code that runs in the renderer,
|
||||
* with access to `getStats()` which returns conversation stats.
|
||||
*/
|
||||
value: string;
|
||||
/** If true, `value` is treated as a JS expression */
|
||||
dynamic?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Metrics available for turn metadata display.
|
||||
*/
|
||||
export type TurnMetric =
|
||||
| 'turnNumber'
|
||||
| 'userCharCount'
|
||||
| 'aiCharCount'
|
||||
| 'codeBlocks'
|
||||
| 'thinkingIndicator'
|
||||
| 'ratio'
|
||||
| 'separator';
|
||||
|
||||
/**
|
||||
* Union type of all integration configurations.
|
||||
*/
|
||||
export type IntegrationConfig =
|
||||
| IButtonIntegration
|
||||
| ITurnMetaIntegration
|
||||
| IUserBadgeIntegration
|
||||
| IBotActionIntegration
|
||||
| IDropdownIntegration
|
||||
| ITitleIntegration;
|
||||
|
||||
// ─── Manager Interface ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Public interface for the Integration Manager.
|
||||
*/
|
||||
export interface IIntegrationManager {
|
||||
/** Register a single integration point */
|
||||
register(config: IntegrationConfig): void;
|
||||
/** Register multiple integration points at once */
|
||||
registerMany(configs: IntegrationConfig[]): void;
|
||||
/** Remove a registered integration by ID */
|
||||
unregister(id: string): void;
|
||||
/** Get all registered integrations */
|
||||
getRegistered(): ReadonlyArray<IntegrationConfig>;
|
||||
/** Generate the integration script from all registered configs */
|
||||
build(): string;
|
||||
/** Install the generated script into workbench.html. Returns true if content changed. */
|
||||
install(): Promise<boolean>;
|
||||
/** Remove the integration from workbench.html */
|
||||
uninstall(): Promise<void>;
|
||||
/** Check if an integration is currently installed */
|
||||
isInstalled(): boolean;
|
||||
}
|
||||
257
antigravity-sdk-main/src/integration/workbench-patcher.ts
Normal file
257
antigravity-sdk-main/src/integration/workbench-patcher.ts
Normal file
@@ -0,0 +1,257 @@
|
||||
/**
|
||||
* Workbench Patcher — Install/uninstall integration scripts into workbench.html.
|
||||
*
|
||||
* Handles the file-level modification of Antigravity's workbench.html
|
||||
* to include/remove custom script tags.
|
||||
*
|
||||
* @module integration/workbench-patcher
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
/** Default prefix for generated files */
|
||||
const FILE_PREFIX = 'ag-sdk';
|
||||
|
||||
/**
|
||||
* Manages patching/unpatching of Antigravity's workbench.html.
|
||||
*/
|
||||
export class WorkbenchPatcher {
|
||||
private readonly _workbenchDir: string;
|
||||
private readonly _workbenchHtml: string;
|
||||
private readonly _scriptPath: string;
|
||||
private readonly _heartbeatPath: string;
|
||||
private readonly _slug: string;
|
||||
|
||||
private readonly _markerStart: string;
|
||||
private readonly _markerEnd: string;
|
||||
|
||||
/**
|
||||
* @param namespace - Unique slug for this extension (e.g. 'kanezal-better-antigravity').
|
||||
* Used to namespace all generated files and HTML markers so multiple
|
||||
* SDK-based extensions can coexist without conflicts.
|
||||
*/
|
||||
constructor(namespace: string = 'default') {
|
||||
// Resolve Antigravity install path
|
||||
const appData = process.env.LOCALAPPDATA || '';
|
||||
this._workbenchDir = path.join(
|
||||
appData,
|
||||
'Programs',
|
||||
'Antigravity',
|
||||
'resources',
|
||||
'app',
|
||||
'out',
|
||||
'vs',
|
||||
'code',
|
||||
'electron-browser',
|
||||
'workbench',
|
||||
);
|
||||
this._workbenchHtml = path.join(this._workbenchDir, 'workbench.html');
|
||||
|
||||
this._slug = namespace.replace(/[^a-zA-Z0-9-]/g, '-');
|
||||
this._scriptPath = path.join(this._workbenchDir, `${FILE_PREFIX}-${this._slug}.js`);
|
||||
this._heartbeatPath = path.join(this._workbenchDir, `${FILE_PREFIX}-${this._slug}-heartbeat`);
|
||||
this._markerStart = `<!-- AG SDK [${this._slug}] -->`;
|
||||
this._markerEnd = `<!-- /AG SDK [${this._slug}] -->`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if workbench.html exists and is accessible.
|
||||
*/
|
||||
isAvailable(): boolean {
|
||||
return fs.existsSync(this._workbenchHtml);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if our integration is currently installed.
|
||||
*/
|
||||
isInstalled(): boolean {
|
||||
if (!this.isAvailable()) return false;
|
||||
try {
|
||||
const content = fs.readFileSync(this._workbenchHtml, 'utf8');
|
||||
return content.includes(this._markerStart);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the integration script.
|
||||
*
|
||||
* 1. Writes the script file to the workbench directory
|
||||
* 2. Patches workbench.html to include a <script> tag
|
||||
*
|
||||
* @param scriptContent — The generated JavaScript code
|
||||
*/
|
||||
install(scriptContent: string): void {
|
||||
if (!this.isAvailable()) {
|
||||
throw new Error(`Workbench not found at: ${this._workbenchDir}`);
|
||||
}
|
||||
|
||||
// First uninstall any previous integration for THIS namespace
|
||||
if (this.isInstalled()) {
|
||||
this.uninstall();
|
||||
}
|
||||
|
||||
// Clean up legacy files from previous versions (non-namespaced)
|
||||
this._cleanupLegacyFiles();
|
||||
|
||||
// Write the script file
|
||||
fs.writeFileSync(this._scriptPath, scriptContent, 'utf8');
|
||||
|
||||
// Patch workbench.html
|
||||
let html = fs.readFileSync(this._workbenchHtml, 'utf8');
|
||||
|
||||
// Insert before </html>
|
||||
const scriptBasename = path.basename(this._scriptPath);
|
||||
const scriptTag = [
|
||||
this._markerStart,
|
||||
`<script src="./${scriptBasename}"></script>`,
|
||||
this._markerEnd,
|
||||
].join('\n');
|
||||
|
||||
html = html.replace('</html>', `${scriptTag}\n</html>`);
|
||||
fs.writeFileSync(this._workbenchHtml, html, 'utf8');
|
||||
|
||||
// Create empty titles JSON if it doesn't exist (prevents console 404)
|
||||
const titlesPath = path.join(this._workbenchDir, `ag-sdk-titles-${this._slug}.json`);
|
||||
if (!fs.existsSync(titlesPath)) {
|
||||
fs.writeFileSync(titlesPath, '{}', 'utf8');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the integration.
|
||||
*
|
||||
* 1. Removes the <script> tag from workbench.html
|
||||
* 2. Deletes the script file
|
||||
*/
|
||||
uninstall(): void {
|
||||
if (!this.isAvailable()) return;
|
||||
|
||||
// Remove from workbench.html
|
||||
try {
|
||||
let html = fs.readFileSync(this._workbenchHtml, 'utf8');
|
||||
const regex = new RegExp(
|
||||
`\\n?${escapeRegex(this._markerStart)}[\\s\\S]*?${escapeRegex(this._markerEnd)}\\n?`,
|
||||
'g',
|
||||
);
|
||||
html = html.replace(regex, '');
|
||||
fs.writeFileSync(this._workbenchHtml, html, 'utf8');
|
||||
} catch {
|
||||
// Ignore errors during cleanup
|
||||
}
|
||||
|
||||
// Remove script file
|
||||
try {
|
||||
if (fs.existsSync(this._scriptPath)) {
|
||||
fs.unlinkSync(this._scriptPath);
|
||||
}
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write/refresh the heartbeat marker file.
|
||||
*
|
||||
* The generated script checks this file's modification time
|
||||
* to determine if the extension is still active. If the file
|
||||
* is missing or stale, the script will not start.
|
||||
*/
|
||||
writeHeartbeat(): void {
|
||||
try {
|
||||
fs.writeFileSync(this._heartbeatPath, Date.now().toString(), 'utf8');
|
||||
} catch {
|
||||
// Ignore — workbench dir may not be writable
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the heartbeat marker file.
|
||||
*/
|
||||
removeHeartbeat(): void {
|
||||
try {
|
||||
if (fs.existsSync(this._heartbeatPath)) {
|
||||
fs.unlinkSync(this._heartbeatPath);
|
||||
}
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to the heartbeat file.
|
||||
*/
|
||||
getHeartbeatPath(): string {
|
||||
return this._heartbeatPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to the workbench directory.
|
||||
*/
|
||||
getWorkbenchDir(): string {
|
||||
return this._workbenchDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to the script file.
|
||||
*/
|
||||
getScriptPath(): string {
|
||||
return this._scriptPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up legacy files from previous SDK versions.
|
||||
*
|
||||
* Removes non-namespaced files (from before namespace support)
|
||||
* and files with wrong namespace (e.g. 'undefined').
|
||||
*/
|
||||
private _cleanupLegacyFiles(): void {
|
||||
// Legacy file names that may exist from older versions
|
||||
const legacyFiles = [
|
||||
'ag-sdk-integrate.js',
|
||||
'ag-sdk-heartbeat',
|
||||
'ag-sdk-titles.json',
|
||||
'ag-sdk-titles-undefined.json',
|
||||
'ag-sdk-titles-default.json',
|
||||
];
|
||||
|
||||
for (const name of legacyFiles) {
|
||||
const p = path.join(this._workbenchDir, name);
|
||||
try {
|
||||
if (fs.existsSync(p)) fs.unlinkSync(p);
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// Remove legacy script tags from workbench.html
|
||||
try {
|
||||
let html = fs.readFileSync(this._workbenchHtml, 'utf8');
|
||||
let changed = false;
|
||||
|
||||
// Remove bare <script src="./ag-sdk-integrate.js"></script> lines
|
||||
const legacyTagRegex = /<script src="\.\/ag-sdk-integrate\.js"><\/script>\n?/g;
|
||||
if (legacyTagRegex.test(html)) {
|
||||
html = html.replace(legacyTagRegex, '');
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// Remove old X-Ray SDK markers with no namespace
|
||||
const xrayRegex = /<!-- X-Ray SDK Integration -->\n?<script[^>]*ag-sdk-integrate[^>]*><\/script>\n?<!-- \/X-Ray SDK Integration -->\n?/g;
|
||||
if (xrayRegex.test(html)) {
|
||||
html = html.replace(xrayRegex, '');
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
fs.writeFileSync(this._workbenchHtml, html, 'utf8');
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
function escapeRegex(str: string): string {
|
||||
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
229
antigravity-sdk-main/src/sdk.ts
Normal file
229
antigravity-sdk-main/src/sdk.ts
Normal file
@@ -0,0 +1,229 @@
|
||||
/**
|
||||
* Main SDK entry point.
|
||||
*
|
||||
* Provides a unified interface to Antigravity's agent system
|
||||
* via verified transport layer (CommandBridge + StateBridge + EventMonitor).
|
||||
*
|
||||
* @module AntigravitySDK
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { AntigravitySDK } from 'antigravity-sdk';
|
||||
*
|
||||
* export function activate(context: vscode.ExtensionContext) {
|
||||
* const sdk = new AntigravitySDK(context);
|
||||
* await sdk.initialize();
|
||||
*
|
||||
* // List conversations
|
||||
* const sessions = await sdk.cascade.getSessions();
|
||||
* console.log(`${sessions.length} conversations`);
|
||||
*
|
||||
* // Read preferences (all 16 sentinel values)
|
||||
* const prefs = await sdk.cascade.getPreferences();
|
||||
* console.log('Terminal policy:', prefs.terminalExecutionPolicy);
|
||||
*
|
||||
* // Monitor for new conversations
|
||||
* sdk.monitor.onNewConversation(() => {
|
||||
* console.log('New conversation detected!');
|
||||
* });
|
||||
* sdk.monitor.start(3000);
|
||||
*
|
||||
* // Clean up
|
||||
* context.subscriptions.push(sdk);
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
|
||||
import * as vscode from 'vscode';
|
||||
import { DisposableStore, IDisposable } from './core/disposable';
|
||||
import { Logger, LogLevel } from './core/logger';
|
||||
import { AntigravityNotFoundError } from './core/errors';
|
||||
import { CommandBridge } from './transport/command-bridge';
|
||||
import { StateBridge } from './transport/state-bridge';
|
||||
import { EventMonitor } from './transport/event-monitor';
|
||||
import { LSBridge } from './transport/ls-bridge';
|
||||
import { CascadeManager } from './cascade/cascade-manager';
|
||||
import { IntegrationManager } from './integration/integration-manager';
|
||||
|
||||
const log = new Logger('SDK');
|
||||
|
||||
/**
|
||||
* SDK initialization options.
|
||||
*/
|
||||
export interface ISDKOptions {
|
||||
/** Enable debug logging */
|
||||
debug?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The main Antigravity SDK class.
|
||||
*
|
||||
* Provides access to:
|
||||
* - `commands` — Execute Antigravity internal commands
|
||||
* - `state` — Read agent preferences and state from USS
|
||||
* - `cascade` — Manage Cascade conversations, send messages, read preferences
|
||||
* - `monitor` — Watch for state changes (new conversations, preference updates)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const sdk = new AntigravitySDK(context);
|
||||
* await sdk.initialize();
|
||||
* const sessions = await sdk.cascade.getSessions();
|
||||
* ```
|
||||
*/
|
||||
export class AntigravitySDK implements IDisposable {
|
||||
private readonly _disposables = new DisposableStore();
|
||||
private _initialized = false;
|
||||
|
||||
/** Command bridge for executing Antigravity commands */
|
||||
public readonly commands: CommandBridge;
|
||||
|
||||
/** State bridge for reading USS data */
|
||||
public readonly state: StateBridge;
|
||||
|
||||
/** Cascade manager for conversations, preferences, diagnostics */
|
||||
public readonly cascade: CascadeManager;
|
||||
|
||||
/** Event monitor for watching state changes */
|
||||
public readonly monitor: EventMonitor;
|
||||
|
||||
/** Integration manager for Agent View UI customization */
|
||||
public readonly integration: IntegrationManager;
|
||||
|
||||
/**
|
||||
* Language Server bridge for headless cascade operations.
|
||||
* Use this for background cascade creation without UI switching.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const id = await sdk.ls.createCascade({ text: 'Analyze coverage' });
|
||||
* await sdk.ls.sendMessage({ cascadeId: id, text: 'Focus on tests' });
|
||||
* await sdk.ls.focusCascade(id); // Only when ready to show
|
||||
* ```
|
||||
*/
|
||||
public readonly ls: LSBridge;
|
||||
|
||||
/**
|
||||
* Create a new Antigravity SDK instance.
|
||||
*
|
||||
* @param context - VS Code extension context
|
||||
* @param options - SDK options
|
||||
*/
|
||||
constructor(
|
||||
private readonly _context: vscode.ExtensionContext,
|
||||
options?: ISDKOptions,
|
||||
) {
|
||||
if (options?.debug) {
|
||||
Logger.setLevel(LogLevel.Debug);
|
||||
}
|
||||
|
||||
// Derive namespace from extension ID for file isolation
|
||||
// e.g. 'kanezal.better-antigravity' -> 'kanezal-better-antigravity'
|
||||
const namespace = this._context.extension.id.replace(/\./g, '-');
|
||||
|
||||
this.commands = this._disposables.add(new CommandBridge());
|
||||
this.state = this._disposables.add(new StateBridge());
|
||||
this.cascade = this._disposables.add(new CascadeManager(this.commands, this.state));
|
||||
this.monitor = this._disposables.add(new EventMonitor(this.state));
|
||||
this.integration = this._disposables.add(new IntegrationManager(namespace));
|
||||
this.ls = new LSBridge(
|
||||
<T = any>(cmd: string, ...args: any[]) => Promise.resolve(vscode.commands.executeCommand<T>(cmd, ...args))
|
||||
);
|
||||
|
||||
log.info(`SDK created (namespace: ${namespace})`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the SDK and verify Antigravity is running.
|
||||
*
|
||||
* Call this before using any SDK features.
|
||||
*
|
||||
* @throws {AntigravityNotFoundError} If Antigravity is not detected
|
||||
*/
|
||||
async initialize(): Promise<void> {
|
||||
if (this._initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
log.info('Initializing SDK...');
|
||||
|
||||
// Verify we're running inside Antigravity
|
||||
const isAntigravity = await this._detectAntigravity();
|
||||
if (!isAntigravity) {
|
||||
throw new AntigravityNotFoundError();
|
||||
}
|
||||
|
||||
// Initialize state bridge (opens state.vscdb via sql.js)
|
||||
await this.state.initialize();
|
||||
|
||||
// Initialize cascade manager (loads session list)
|
||||
await this.cascade.initialize();
|
||||
|
||||
// Initialize LS bridge (discovers Language Server port + CSRF token)
|
||||
const lsOk = await this.ls.initialize();
|
||||
if (lsOk) {
|
||||
log.info(`LS bridge ready on port ${this.ls.port} (csrf: ${this.ls.hasCsrfToken ? 'ok' : 'missing'})`);
|
||||
} else {
|
||||
log.warn('LS bridge not available — use sdk.ls.setConnection(port, csrfToken) or command fallback');
|
||||
}
|
||||
|
||||
// Refresh integration heartbeat (so renderer script knows extension is active)
|
||||
this.integration.signalActive();
|
||||
|
||||
this._initialized = true;
|
||||
log.info('SDK initialized successfully');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the SDK has been initialized.
|
||||
*/
|
||||
get isInitialized(): boolean {
|
||||
return this._initialized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the SDK version.
|
||||
*/
|
||||
get version(): string {
|
||||
try {
|
||||
return require('../package.json').version;
|
||||
} catch {
|
||||
return 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect if we're running inside Antigravity IDE.
|
||||
*/
|
||||
private async _detectAntigravity(): Promise<boolean> {
|
||||
try {
|
||||
// Check for Antigravity-specific commands (VERIFIED naming)
|
||||
const commands = await this.commands.getAntigravityCommands();
|
||||
const hasAgentPanel = commands.includes('antigravity.agentPanel.open');
|
||||
|
||||
if (hasAgentPanel) {
|
||||
log.debug(`Detected Antigravity (${commands.length} commands)`);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Fallback: check env
|
||||
const appName = vscode.env.appName;
|
||||
if (appName?.toLowerCase().includes('antigravity')) {
|
||||
log.debug(`Detected Antigravity via appName: ${appName}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispose of the SDK and all its resources.
|
||||
*/
|
||||
dispose(): void {
|
||||
log.info('Disposing SDK');
|
||||
this._disposables.dispose();
|
||||
}
|
||||
}
|
||||
342
antigravity-sdk-main/src/transport/command-bridge.ts
Normal file
342
antigravity-sdk-main/src/transport/command-bridge.ts
Normal file
@@ -0,0 +1,342 @@
|
||||
/**
|
||||
* Command Bridge — executes Antigravity internal commands via VS Code API.
|
||||
*
|
||||
* All commands go through `vscode.commands.executeCommand()` which is the
|
||||
* safe, official way to interact with Antigravity from extensions.
|
||||
*
|
||||
* VERIFIED: All commands listed below were confirmed to exist in
|
||||
* Antigravity v1.107.0 workbench.desktop.main.js and extension.js
|
||||
* on 2026-02-28.
|
||||
*
|
||||
* @module transport/command-bridge
|
||||
*/
|
||||
|
||||
import * as vscode from 'vscode';
|
||||
import { IDisposable } from '../core/disposable';
|
||||
import { CommandExecutionError } from '../core/errors';
|
||||
import { Logger } from '../core/logger';
|
||||
|
||||
const log = new Logger('CommandBridge');
|
||||
|
||||
/**
|
||||
* All known Antigravity commands, organized by category.
|
||||
*
|
||||
* Sources: workbench.desktop.main.js (160+ commands) + extension.js (45 commands)
|
||||
*/
|
||||
export const AntigravityCommands = {
|
||||
|
||||
// ─── Agent Panel & UI (VERIFIED: .open/.focus suffix required) ────────
|
||||
|
||||
/** Open the Cascade agent panel */
|
||||
OPEN_AGENT_PANEL: 'antigravity.agentPanel.open',
|
||||
/** Focus the Cascade agent panel */
|
||||
FOCUS_AGENT_PANEL: 'antigravity.agentPanel.focus',
|
||||
/** Open the agent side panel */
|
||||
OPEN_AGENT_SIDE_PANEL: 'antigravity.agentSidePanel.open',
|
||||
/** Focus the agent side panel */
|
||||
FOCUS_AGENT_SIDE_PANEL: 'antigravity.agentSidePanel.focus',
|
||||
/** Toggle side panel visibility */
|
||||
TOGGLE_SIDE_PANEL: 'antigravity.agentSidePanel.toggleVisibility',
|
||||
/** Open agent (generic) */
|
||||
OPEN_AGENT: 'antigravity.openAgent',
|
||||
/** Toggle chat focus */
|
||||
TOGGLE_CHAT_FOCUS: 'antigravity.toggleChatFocus',
|
||||
/** Switch between workspace editor and agent view */
|
||||
SWITCH_WORKSPACE_AGENT: 'antigravity.switchBetweenWorkspaceAndAgent',
|
||||
|
||||
// ─── Conversation Management (Critical for SDK) ──────────────────────
|
||||
|
||||
/** Start a new conversation */
|
||||
START_NEW_CONVERSATION: 'antigravity.startNewConversation',
|
||||
/** Send a prompt to the agent panel */
|
||||
SEND_PROMPT_TO_AGENT: 'antigravity.sendPromptToAgentPanel',
|
||||
/** Send text to chat */
|
||||
SEND_TEXT_TO_CHAT: 'antigravity.sendTextToChat',
|
||||
/** Send a chat action message */
|
||||
SEND_CHAT_ACTION: 'antigravity.sendChatActionMessage',
|
||||
/** Set which conversation is visible */
|
||||
SET_VISIBLE_CONVERSATION: 'antigravity.setVisibleConversation',
|
||||
/** Execute a cascade action */
|
||||
EXECUTE_CASCADE_ACTION: 'antigravity.executeCascadeAction',
|
||||
/** Broadcast conversation deletion to all windows */
|
||||
BROADCAST_CONVERSATION_DELETION: 'antigravity.broadcastConversationDeletion',
|
||||
/** Track that a background conversation was created */
|
||||
TRACK_BACKGROUND_CONVERSATION: 'antigravity.trackBackgroundConversationCreated',
|
||||
|
||||
// ─── Agent Step Control (VERIFIED) ────────────────────────────────────
|
||||
|
||||
/** Accept the current agent step */
|
||||
ACCEPT_AGENT_STEP: 'antigravity.agent.acceptAgentStep',
|
||||
/** Reject the current agent step */
|
||||
REJECT_AGENT_STEP: 'antigravity.agent.rejectAgentStep',
|
||||
/** Accept a pending command */
|
||||
COMMAND_ACCEPT: 'antigravity.command.accept',
|
||||
/** Reject a pending command */
|
||||
COMMAND_REJECT: 'antigravity.command.reject',
|
||||
/** Accept a terminal command */
|
||||
TERMINAL_ACCEPT: 'antigravity.terminalCommand.accept',
|
||||
/** Reject a terminal command */
|
||||
TERMINAL_REJECT: 'antigravity.terminalCommand.reject',
|
||||
/** Run a terminal command */
|
||||
TERMINAL_RUN: 'antigravity.terminalCommand.run',
|
||||
/** Open new conversation (prioritized) */
|
||||
OPEN_NEW_CONVERSATION: 'antigravity.prioritized.chat.openNewConversation',
|
||||
|
||||
// ─── Terminal Integration ─────────────────────────────────────────────
|
||||
|
||||
/** Notify terminal command started */
|
||||
TERMINAL_COMMAND_START: 'antigravity.onManagerTerminalCommandStart',
|
||||
/** Notify terminal command data */
|
||||
TERMINAL_COMMAND_DATA: 'antigravity.onManagerTerminalCommandData',
|
||||
/** Notify terminal command finished */
|
||||
TERMINAL_COMMAND_FINISH: 'antigravity.onManagerTerminalCommandFinish',
|
||||
/** Update last terminal command */
|
||||
UPDATE_TERMINAL_LAST_COMMAND: 'antigravity.updateTerminalLastCommand',
|
||||
/** Notify shell command completion */
|
||||
ON_SHELL_COMPLETION: 'antigravity.onShellCommandCompletion',
|
||||
/** Show managed terminal */
|
||||
SHOW_MANAGED_TERMINAL: 'antigravity.showManagedTerminal',
|
||||
/** Send terminal output to chat */
|
||||
SEND_TERMINAL_TO_CHAT: 'antigravity.sendTerminalToChat',
|
||||
/** Send terminal output to side panel */
|
||||
SEND_TERMINAL_TO_SIDE_PANEL: 'antigravity.sendTerminalToSidePanel',
|
||||
|
||||
// ─── Agent & Mode ─────────────────────────────────────────────────────
|
||||
|
||||
/** Initialize the agent */
|
||||
INITIALIZE_AGENT: 'antigravity.initializeAgent',
|
||||
|
||||
// ─── Conversation Picker & Workspace ──────────────────────────────────
|
||||
|
||||
/** Open conversation workspace picker */
|
||||
OPEN_CONVERSATION_PICKER: 'antigravity.openConversationWorkspaceQuickPick',
|
||||
/** Open conversation picker (alternative) */
|
||||
OPEN_CONV_PICKER_ALT: 'antigravity.openConversationPicker',
|
||||
/** Set working directories */
|
||||
SET_WORKING_DIRS: 'antigravity.setWorkingDirectories',
|
||||
|
||||
// ─── Review & Diff ────────────────────────────────────────────────────
|
||||
|
||||
/** Open review changes view */
|
||||
OPEN_REVIEW_CHANGES: 'antigravity.openReviewChanges',
|
||||
/** Open diff view */
|
||||
OPEN_DIFF_VIEW: 'antigravity.openDiffView',
|
||||
/** Open diff zones */
|
||||
OPEN_DIFF_ZONES: 'antigravity.openDiffZones',
|
||||
/** Close all diff zones */
|
||||
CLOSE_ALL_DIFF_ZONES: 'antigravity.closeAllDiffZones',
|
||||
|
||||
// ─── Rules & Workflows ────────────────────────────────────────────────
|
||||
|
||||
/** Create a new rule */
|
||||
CREATE_RULE: 'antigravity.createRule',
|
||||
/** Create a new workflow */
|
||||
CREATE_WORKFLOW: 'antigravity.createWorkflow',
|
||||
/** Create a global workflow */
|
||||
CREATE_GLOBAL_WORKFLOW: 'antigravity.createGlobalWorkflow',
|
||||
/** Open global rules */
|
||||
OPEN_GLOBAL_RULES: 'antigravity.openGlobalRules',
|
||||
/** Open workspace rules */
|
||||
OPEN_WORKSPACE_RULES: 'antigravity.openWorkspaceRules',
|
||||
|
||||
// ─── Plugins & MCP ────────────────────────────────────────────────────
|
||||
|
||||
/** Open configure plugins page */
|
||||
OPEN_CONFIGURE_PLUGINS: 'antigravity.openConfigurePluginsPage',
|
||||
/** Get Cascade plugin template */
|
||||
GET_PLUGIN_TEMPLATE: 'antigravity.getCascadePluginTemplate',
|
||||
/** Poll MCP server states */
|
||||
POLL_MCP_SERVERS: 'antigravity.pollMcpServerStates',
|
||||
/** Open MCP config file */
|
||||
OPEN_MCP_CONFIG: 'antigravity.openMcpConfigFile',
|
||||
/** Open MCP docs page */
|
||||
OPEN_MCP_DOCS: 'antigravity.openMcpDocsPage',
|
||||
/** Update plugin installation count */
|
||||
UPDATE_PLUGIN_COUNT: 'antigravity.updatePluginInstallationCount',
|
||||
|
||||
// ─── Autocomplete ─────────────────────────────────────────────────────
|
||||
|
||||
/** Enable autocomplete */
|
||||
ENABLE_AUTOCOMPLETE: 'antigravity.enableAutocomplete',
|
||||
/** Disable autocomplete */
|
||||
DISABLE_AUTOCOMPLETE: 'antigravity.disableAutocomplete',
|
||||
/** Accept completion */
|
||||
ACCEPT_COMPLETION: 'antigravity.acceptCompletion',
|
||||
/** Force supercomplete */
|
||||
FORCE_SUPERCOMPLETE: 'antigravity.forceSupercomplete',
|
||||
/** Snooze autocomplete temporarily */
|
||||
SNOOZE_AUTOCOMPLETE: 'antigravity.snoozeAutocomplete',
|
||||
/** Cancel snooze */
|
||||
CANCEL_SNOOZE: 'antigravity.cancelSnoozeAutocomplete',
|
||||
|
||||
// ─── Auth & Account ───────────────────────────────────────────────────
|
||||
|
||||
/** Login to Antigravity */
|
||||
LOGIN: 'antigravity.login',
|
||||
/** Cancel login */
|
||||
CANCEL_LOGIN: 'antigravity.cancelLogin',
|
||||
/** Handle auth refresh */
|
||||
HANDLE_AUTH_REFRESH: 'antigravity.handleAuthRefresh',
|
||||
/** Sign in to Antigravity */
|
||||
SIGN_IN: 'antigravity.SignInToAntigravity',
|
||||
|
||||
// ─── Diagnostics & Debug ──────────────────────────────────────────────
|
||||
|
||||
/** Get diagnostics info */
|
||||
GET_DIAGNOSTICS: 'antigravity.getDiagnostics',
|
||||
/** Download diagnostics bundle */
|
||||
DOWNLOAD_DIAGNOSTICS: 'antigravity.downloadDiagnostics',
|
||||
/** Capture traces */
|
||||
CAPTURE_TRACES: 'antigravity.captureTraces',
|
||||
/** Enable tracing */
|
||||
ENABLE_TRACING: 'antigravity.enableTracing',
|
||||
/** Clear and disable tracing */
|
||||
CLEAR_TRACING: 'antigravity.clearAndDisableTracing',
|
||||
/** Get manager trace */
|
||||
GET_MANAGER_TRACE: 'antigravity.getManagerTrace',
|
||||
/** Get workbench trace */
|
||||
GET_WORKBENCH_TRACE: 'antigravity.getWorkbenchTrace',
|
||||
/** Toggle debug info widget */
|
||||
TOGGLE_DEBUG_INFO: 'antigravity.toggleDebugInfoWidget',
|
||||
/** Open troubleshooting */
|
||||
OPEN_TROUBLESHOOTING: 'antigravity.openTroubleshooting',
|
||||
/** Open issue reporter */
|
||||
OPEN_ISSUE_REPORTER: 'antigravity.openIssueReporter',
|
||||
|
||||
// ─── Language Server ──────────────────────────────────────────────────
|
||||
|
||||
/** Restart the language server */
|
||||
RESTART_LANGUAGE_SERVER: 'antigravity.restartLanguageServer',
|
||||
/** Kill language server and reload window */
|
||||
KILL_LS_AND_RELOAD: 'antigravity.killLanguageServerAndReloadWindow',
|
||||
|
||||
// ─── Git & Commit ─────────────────────────────────────────────────────
|
||||
|
||||
/** Generate commit message via AI */
|
||||
GENERATE_COMMIT_MESSAGE: 'antigravity.generateCommitMessage',
|
||||
/** Cancel commit message generation */
|
||||
CANCEL_COMMIT_MESSAGE: 'antigravity.cancelGenerateCommitMessage',
|
||||
|
||||
// ─── Browser ──────────────────────────────────────────────────────────
|
||||
|
||||
/** Open browser */
|
||||
OPEN_BROWSER: 'antigravity.openBrowser',
|
||||
/** Get browser onboarding port (returns number, e.g. 57401) */
|
||||
GET_BROWSER_PORT: 'antigravity.getBrowserOnboardingPort',
|
||||
|
||||
// ─── Settings & Import ────────────────────────────────────────────────
|
||||
|
||||
/** Open quick settings panel */
|
||||
OPEN_QUICK_SETTINGS: 'antigravity.openQuickSettingsPanel',
|
||||
/** Open customizations tab */
|
||||
OPEN_CUSTOMIZATIONS: 'antigravity.openCustomizationsTab',
|
||||
/** Import VS Code settings */
|
||||
IMPORT_VSCODE_SETTINGS: 'antigravity.importVSCodeSettings',
|
||||
/** Import VS Code extensions */
|
||||
IMPORT_VSCODE_EXTENSIONS: 'antigravity.importVSCodeExtensions',
|
||||
/** Import Cursor settings */
|
||||
IMPORT_CURSOR_SETTINGS: 'antigravity.importCursorSettings',
|
||||
/** Import Cursor extensions */
|
||||
IMPORT_CURSOR_EXTENSIONS: 'antigravity.importCursorExtensions',
|
||||
|
||||
// ─── Misc ─────────────────────────────────────────────────────────────
|
||||
|
||||
/** Reload window */
|
||||
RELOAD_WINDOW: 'antigravity.reloadWindow',
|
||||
/** Open documentation */
|
||||
OPEN_DOCS: 'antigravity.openDocs',
|
||||
/** Open changelog */
|
||||
OPEN_CHANGELOG: 'antigravity.openChangeLog',
|
||||
/** Explain and fix problem (from diagnostics) */
|
||||
EXPLAIN_AND_FIX: 'antigravity.explainAndFixProblem',
|
||||
/** Open a URL */
|
||||
OPEN_URL: 'antigravity.openGenericUrl',
|
||||
/** Editor mode settings */
|
||||
EDITOR_MODE_SETTINGS: 'antigravity.editorModeSettings',
|
||||
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Bridges between the SDK and Antigravity's command system.
|
||||
*
|
||||
* All interactions with Antigravity go through registered VS Code commands,
|
||||
* ensuring we never bypass the official extension API.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const bridge = new CommandBridge();
|
||||
*
|
||||
* // Open the agent panel
|
||||
* await bridge.execute(AntigravityCommands.OPEN_AGENT_PANEL);
|
||||
*
|
||||
* // Start a new conversation
|
||||
* await bridge.execute(AntigravityCommands.START_NEW_CONVERSATION);
|
||||
*
|
||||
* // Send a prompt
|
||||
* await bridge.execute(AntigravityCommands.SEND_PROMPT_TO_AGENT, 'Hello!');
|
||||
* ```
|
||||
*/
|
||||
export class CommandBridge implements IDisposable {
|
||||
private _disposed = false;
|
||||
|
||||
/**
|
||||
* Execute an Antigravity command.
|
||||
*
|
||||
* @param command - The command ID to execute
|
||||
* @param args - Arguments to pass to the command
|
||||
* @returns The command's return value
|
||||
* @throws {CommandExecutionError} If the command fails
|
||||
*/
|
||||
async execute<T = unknown>(command: string, ...args: unknown[]): Promise<T> {
|
||||
if (this._disposed) {
|
||||
throw new CommandExecutionError(command, 'CommandBridge has been disposed');
|
||||
}
|
||||
|
||||
log.debug(`Executing: ${command}`, args.length > 0 ? args : '');
|
||||
|
||||
try {
|
||||
const result = await vscode.commands.executeCommand<T>(command, ...args);
|
||||
return result;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
log.error(`Command failed: ${command}`, message);
|
||||
throw new CommandExecutionError(command, message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a command is registered and available.
|
||||
*
|
||||
* @param command - Command ID to check
|
||||
* @returns true if the command exists
|
||||
*/
|
||||
async isAvailable(command: string): Promise<boolean> {
|
||||
const commands = await vscode.commands.getCommands(true);
|
||||
return commands.includes(command);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered Antigravity commands.
|
||||
*
|
||||
* @returns List of command IDs starting with 'antigravity.'
|
||||
*/
|
||||
async getAntigravityCommands(): Promise<string[]> {
|
||||
const commands = await vscode.commands.getCommands(true);
|
||||
return commands.filter((cmd) => cmd.startsWith('antigravity.'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a command handler.
|
||||
*
|
||||
* @param command - Command ID to register
|
||||
* @param handler - Function to handle the command
|
||||
* @returns Disposable to unregister the command
|
||||
*/
|
||||
register(command: string, handler: (...args: unknown[]) => unknown): IDisposable {
|
||||
return vscode.commands.registerCommand(command, handler);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this._disposed = true;
|
||||
}
|
||||
}
|
||||
307
antigravity-sdk-main/src/transport/event-monitor.ts
Normal file
307
antigravity-sdk-main/src/transport/event-monitor.ts
Normal file
@@ -0,0 +1,307 @@
|
||||
/**
|
||||
* Event Monitor — polls state.vscdb and getDiagnostics for changes.
|
||||
*
|
||||
* Detects:
|
||||
* - USS key changes (trajectory summaries, preferences, etc.)
|
||||
* - Step count changes per session (via getDiagnostics.recentTrajectories)
|
||||
* - Active session switches
|
||||
* - New conversations
|
||||
*
|
||||
* @module transport/event-monitor
|
||||
*/
|
||||
|
||||
import * as vscode from 'vscode';
|
||||
import { IDisposable, DisposableStore } from '../core/disposable';
|
||||
import { EventEmitter, Event } from '../core/events';
|
||||
import { Logger } from '../core/logger';
|
||||
import { StateBridge, USSKeys } from './state-bridge';
|
||||
|
||||
const log = new Logger('EventMonitor');
|
||||
|
||||
/**
|
||||
* USS key change event.
|
||||
*/
|
||||
export interface IStateChange {
|
||||
/** Which USS key changed */
|
||||
readonly key: string;
|
||||
/** New data size */
|
||||
readonly newSize: number;
|
||||
/** Previous data size */
|
||||
readonly previousSize: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Step count change event — fired when the agent adds/processes steps.
|
||||
*/
|
||||
export interface IStepCountChange {
|
||||
/** Conversation UUID (googleAgentId) */
|
||||
readonly sessionId: string;
|
||||
/** Conversation title */
|
||||
readonly title: string;
|
||||
/** Previous step count */
|
||||
readonly previousCount: number;
|
||||
/** New step count */
|
||||
readonly newCount: number;
|
||||
/** Number of new steps added */
|
||||
readonly delta: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Active session change event.
|
||||
*/
|
||||
export interface IActiveSessionChange {
|
||||
/** New active session ID */
|
||||
readonly sessionId: string;
|
||||
/** New active session title */
|
||||
readonly title: string;
|
||||
/** Previous active session ID (empty if first detection) */
|
||||
readonly previousSessionId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot of a trajectory from getDiagnostics.
|
||||
*/
|
||||
interface ITrajectorySnapshot {
|
||||
id: string;
|
||||
title: string;
|
||||
stepCount: number;
|
||||
lastModified: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Monitors Antigravity state for changes.
|
||||
*
|
||||
* Two polling modes:
|
||||
* 1. **USS polling** — watches state.vscdb keys for size changes (lightweight)
|
||||
* 2. **Trajectory polling** — watches getDiagnostics for step count changes (heavier, optional)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const monitor = new EventMonitor(stateBridge);
|
||||
*
|
||||
* // React to step changes (agent is working)
|
||||
* monitor.onStepCountChanged((e) => {
|
||||
* console.log(`${e.title}: +${e.delta} steps (now ${e.newCount})`);
|
||||
* });
|
||||
*
|
||||
* // React to conversation switches
|
||||
* monitor.onActiveSessionChanged((e) => {
|
||||
* console.log(`Switched to: ${e.title}`);
|
||||
* });
|
||||
*
|
||||
* monitor.start(3000);
|
||||
* ```
|
||||
*/
|
||||
export class EventMonitor implements IDisposable {
|
||||
private readonly _disposables = new DisposableStore();
|
||||
private _ussTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private _trajTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private _ussSnapshots = new Map<string, number>();
|
||||
private _trajSnapshots = new Map<string, ITrajectorySnapshot>();
|
||||
private _activeSessionId = '';
|
||||
private _running = false;
|
||||
|
||||
// ─── USS Events ─────────────────────────────────────────────────────
|
||||
|
||||
private readonly _onStateChanged = this._disposables.add(new EventEmitter<IStateChange>());
|
||||
/** Fires when any monitored USS key changes size */
|
||||
public readonly onStateChanged: Event<IStateChange> = this._onStateChanged.event;
|
||||
|
||||
private readonly _onNewConversation = this._disposables.add(new EventEmitter<void>());
|
||||
/** Fires when trajectory summaries grow (new conversation likely) */
|
||||
public readonly onNewConversation: Event<void> = this._onNewConversation.event;
|
||||
|
||||
// ─── Trajectory Events ──────────────────────────────────────────────
|
||||
|
||||
private readonly _onStepCountChanged = this._disposables.add(new EventEmitter<IStepCountChange>());
|
||||
/** Fires when a session's step count changes (agent made progress) */
|
||||
public readonly onStepCountChanged: Event<IStepCountChange> = this._onStepCountChanged.event;
|
||||
|
||||
private readonly _onActiveSessionChanged = this._disposables.add(new EventEmitter<IActiveSessionChange>());
|
||||
/** Fires when the active (most recent) session changes */
|
||||
public readonly onActiveSessionChanged: Event<IActiveSessionChange> = this._onActiveSessionChanged.event;
|
||||
|
||||
/** Keys we monitor for USS changes */
|
||||
private readonly _watchedKeys = [
|
||||
USSKeys.TRAJECTORY_SUMMARIES,
|
||||
USSKeys.AGENT_PREFERENCES,
|
||||
USSKeys.USER_STATUS,
|
||||
];
|
||||
|
||||
constructor(private readonly _state: StateBridge) { }
|
||||
|
||||
/**
|
||||
* Start polling for state changes.
|
||||
*
|
||||
* @param intervalMs - USS polling interval (default: 3000ms)
|
||||
* @param trajectoryIntervalMs - Trajectory polling interval (default: 5000ms).
|
||||
* Set to 0 to disable trajectory polling (saves CPU).
|
||||
*/
|
||||
start(intervalMs: number = 3000, trajectoryIntervalMs: number = 5000): void {
|
||||
if (this._running) return;
|
||||
|
||||
this._running = true;
|
||||
log.info(`Starting event monitor (USS: ${intervalMs}ms, Traj: ${trajectoryIntervalMs}ms)`);
|
||||
|
||||
// Initial USS snapshot
|
||||
this._takeUSSSnapshot().catch(() => { });
|
||||
|
||||
// USS polling
|
||||
this._ussTimer = setInterval(async () => {
|
||||
try {
|
||||
await this._pollUSS();
|
||||
} catch (error) {
|
||||
log.error('USS poll error', error);
|
||||
}
|
||||
}, intervalMs);
|
||||
|
||||
// Trajectory polling (optional, heavier)
|
||||
if (trajectoryIntervalMs > 0) {
|
||||
this._pollTrajectories().catch(() => { });
|
||||
|
||||
this._trajTimer = setInterval(async () => {
|
||||
try {
|
||||
await this._pollTrajectories();
|
||||
} catch (error) {
|
||||
log.error('Trajectory poll error', error);
|
||||
}
|
||||
}, trajectoryIntervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop polling.
|
||||
*/
|
||||
stop(): void {
|
||||
if (this._ussTimer) {
|
||||
clearInterval(this._ussTimer);
|
||||
this._ussTimer = null;
|
||||
}
|
||||
if (this._trajTimer) {
|
||||
clearInterval(this._trajTimer);
|
||||
this._trajTimer = null;
|
||||
}
|
||||
this._running = false;
|
||||
log.info('Event monitor stopped');
|
||||
}
|
||||
|
||||
/** Check if the monitor is currently running. */
|
||||
get isRunning(): boolean {
|
||||
return this._running;
|
||||
}
|
||||
|
||||
/** Get the currently active session ID. */
|
||||
get activeSessionId(): string {
|
||||
return this._activeSessionId;
|
||||
}
|
||||
|
||||
// ─── USS Polling ────────────────────────────────────────────────────
|
||||
|
||||
private async _takeUSSSnapshot(): Promise<void> {
|
||||
for (const key of this._watchedKeys) {
|
||||
try {
|
||||
const value = await this._state.getRawValue(key);
|
||||
this._ussSnapshots.set(key, value ? value.length : 0);
|
||||
} catch {
|
||||
this._ussSnapshots.set(key, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async _pollUSS(): Promise<void> {
|
||||
for (const key of this._watchedKeys) {
|
||||
try {
|
||||
const value = await this._state.getRawValue(key);
|
||||
const newSize = value ? value.length : 0;
|
||||
const previousSize = this._ussSnapshots.get(key) ?? 0;
|
||||
|
||||
if (newSize !== previousSize) {
|
||||
log.debug(`USS change: ${key} (${previousSize} -> ${newSize})`);
|
||||
this._ussSnapshots.set(key, newSize);
|
||||
this._onStateChanged.fire({ key, newSize, previousSize });
|
||||
|
||||
if (key === USSKeys.TRAJECTORY_SUMMARIES && newSize > previousSize) {
|
||||
this._onNewConversation.fire();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Skip errors during polling
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Trajectory Polling ─────────────────────────────────────────────
|
||||
|
||||
private async _pollTrajectories(): Promise<void> {
|
||||
let trajectories: Array<{
|
||||
googleAgentId: string;
|
||||
trajectoryId: string;
|
||||
summary: string;
|
||||
lastStepIndex: number;
|
||||
lastModifiedTime: string;
|
||||
}>;
|
||||
|
||||
try {
|
||||
const raw = await vscode.commands.executeCommand<string>('antigravity.getDiagnostics');
|
||||
if (!raw || typeof raw !== 'string') return;
|
||||
const diag = JSON.parse(raw);
|
||||
if (!Array.isArray(diag.recentTrajectories)) return;
|
||||
trajectories = diag.recentTrajectories;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for step count changes in each trajectory
|
||||
for (const traj of trajectories) {
|
||||
const id = traj.googleAgentId;
|
||||
if (!id) continue;
|
||||
|
||||
const prev = this._trajSnapshots.get(id);
|
||||
const newCount = traj.lastStepIndex ?? 0;
|
||||
|
||||
if (prev && prev.stepCount !== newCount) {
|
||||
const delta = newCount - prev.stepCount;
|
||||
log.debug(`Step change: "${traj.summary}" ${prev.stepCount} -> ${newCount} (+${delta})`);
|
||||
|
||||
this._onStepCountChanged.fire({
|
||||
sessionId: id,
|
||||
title: traj.summary ?? 'Untitled',
|
||||
previousCount: prev.stepCount,
|
||||
newCount,
|
||||
delta,
|
||||
});
|
||||
}
|
||||
|
||||
this._trajSnapshots.set(id, {
|
||||
id,
|
||||
title: traj.summary ?? 'Untitled',
|
||||
stepCount: newCount,
|
||||
lastModified: traj.lastModifiedTime ?? '',
|
||||
});
|
||||
}
|
||||
|
||||
// Check for active session change (first entry = most recent)
|
||||
if (trajectories.length > 0) {
|
||||
const newActiveId = trajectories[0].googleAgentId;
|
||||
if (newActiveId && newActiveId !== this._activeSessionId) {
|
||||
const previousId = this._activeSessionId;
|
||||
this._activeSessionId = newActiveId;
|
||||
|
||||
// Only fire event after initial snapshot (not on first detection)
|
||||
if (previousId !== '') {
|
||||
log.debug(`Active session changed: "${trajectories[0].summary}"`);
|
||||
this._onActiveSessionChanged.fire({
|
||||
sessionId: newActiveId,
|
||||
title: trajectories[0].summary ?? 'Untitled',
|
||||
previousSessionId: previousId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.stop();
|
||||
this._disposables.dispose();
|
||||
}
|
||||
}
|
||||
9
antigravity-sdk-main/src/transport/index.ts
Normal file
9
antigravity-sdk-main/src/transport/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Transport module re-exports.
|
||||
* @module transport
|
||||
*/
|
||||
|
||||
export { CommandBridge, AntigravityCommands } from './command-bridge';
|
||||
export { StateBridge, USSKeys } from './state-bridge';
|
||||
export { EventMonitor, type IStateChange } from './event-monitor';
|
||||
export { LSBridge, Models, type ModelId, type IHeadlessCascadeOptions, type ISendMessageOptions } from './ls-bridge';
|
||||
725
antigravity-sdk-main/src/transport/ls-bridge.ts
Normal file
725
antigravity-sdk-main/src/transport/ls-bridge.ts
Normal file
@@ -0,0 +1,725 @@
|
||||
/**
|
||||
* Language Server Bridge — Direct ConnectRPC calls to the local LS.
|
||||
*
|
||||
* UPDATED 2026-03-01 (v1.3.0):
|
||||
* Fixed CSRF token authentication (Issue #1).
|
||||
* The LS binary is launched with --csrf_token as a CLI argument.
|
||||
* Previous versions did not send this token, causing 401 "missing CSRF token".
|
||||
*
|
||||
* Discovery strategy (multi-layer):
|
||||
* 1. Process CLI args — extract --port and --csrf_token from LS process
|
||||
* 2. getDiagnostics console logs — fallback for port discovery
|
||||
* 3. Manual override — setConnection(port, csrfToken)
|
||||
*
|
||||
* Service: exa.language_server_pb.LanguageServerService
|
||||
* Protocol: HTTPS POST with JSON body + x-csrf-token header
|
||||
*
|
||||
* @module transport/ls-bridge
|
||||
*/
|
||||
|
||||
import { Logger } from '../core/logger';
|
||||
|
||||
const log = new Logger('LSBridge');
|
||||
|
||||
/** Known model IDs (verified 2026-02-28) */
|
||||
export const Models = {
|
||||
GEMINI_FLASH: 1018,
|
||||
GEMINI_PRO_LOW: 1164,
|
||||
GEMINI_PRO_HIGH: 1165,
|
||||
CLAUDE_SONNET: 1163,
|
||||
CLAUDE_OPUS: 1154,
|
||||
GPT_OSS: 342,
|
||||
} as const;
|
||||
|
||||
export type ModelId = typeof Models[keyof typeof Models] | number;
|
||||
|
||||
/** Options for creating a headless cascade */
|
||||
export interface IHeadlessCascadeOptions {
|
||||
/** Text prompt to send */
|
||||
text: string;
|
||||
/** Model ID (default: Gemini 3 Flash = 1018) */
|
||||
model?: ModelId;
|
||||
/** Planner type: 'conversational' (default) or 'normal' */
|
||||
plannerType?: 'conversational' | 'normal';
|
||||
}
|
||||
|
||||
/** Options for sending a message to existing cascade */
|
||||
export interface ISendMessageOptions {
|
||||
/** Target cascade ID */
|
||||
cascadeId: string;
|
||||
/** Text to send */
|
||||
text: string;
|
||||
/** Model ID (default: Gemini 3 Flash = 1018) */
|
||||
model?: ModelId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Conversation annotation fields (from jetski_cortex.proto ConversationAnnotations).
|
||||
*
|
||||
* These are metadata annotations on a conversation that the user can set.
|
||||
* The LS stores these natively and they persist across sessions.
|
||||
*/
|
||||
export interface IConversationAnnotations {
|
||||
/** Custom user title -- overrides the auto-generated summary */
|
||||
title?: string;
|
||||
/** Tags/labels for organization */
|
||||
tags?: string[];
|
||||
/** Whether this conversation is archived */
|
||||
archived?: boolean;
|
||||
/** Whether this conversation is starred (pinned) */
|
||||
starred?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Direct bridge to the Language Server via ConnectRPC.
|
||||
*
|
||||
* Discovers the LS port and CSRF token from the LS process CLI args,
|
||||
* then makes authenticated HTTPS POST calls to the LS endpoints.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const ls = new LSBridge(commandBridge);
|
||||
* await ls.initialize();
|
||||
*
|
||||
* // Create a headless cascade
|
||||
* const cascadeId = await ls.createCascade({
|
||||
* text: 'Analyze test coverage',
|
||||
* model: Models.GEMINI_FLASH,
|
||||
* });
|
||||
*
|
||||
* // Send follow-up
|
||||
* await ls.sendMessage({ cascadeId, text: 'Focus on edge cases' });
|
||||
*
|
||||
* // Switch UI to it
|
||||
* await ls.focusCascade(cascadeId);
|
||||
* ```
|
||||
*/
|
||||
export class LSBridge {
|
||||
private _port: number | null = null;
|
||||
private _csrfToken: string | null = null;
|
||||
private _useTls: boolean = false;
|
||||
private _executeCommand: <T = any>(command: string, ...args: any[]) => Promise<T>;
|
||||
|
||||
constructor(executeCommand: <T = any>(command: string, ...args: any[]) => Promise<T>) {
|
||||
this._executeCommand = executeCommand;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover the Language Server port and CSRF token.
|
||||
* Must be called before other methods.
|
||||
*
|
||||
* Discovery chain:
|
||||
* 1. Parse LS process CLI arguments (--port, --csrf_token)
|
||||
* 2. Fallback: getDiagnostics console logs (port only)
|
||||
* 3. Manual: call setConnection() after initialize() returns false
|
||||
*/
|
||||
async initialize(): Promise<boolean> {
|
||||
// Strategy 1: discover from LS process CLI args (port + CSRF)
|
||||
const fromProcess = await this._discoverFromProcess();
|
||||
if (fromProcess) {
|
||||
this._port = fromProcess.port;
|
||||
this._csrfToken = fromProcess.csrfToken;
|
||||
this._useTls = fromProcess.useTls;
|
||||
log.info(`LS discovered from process: port=${this._port}, tls=${this._useTls}, csrf=${this._csrfToken ? 'found' : 'missing'}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Strategy 2: fallback to getDiagnostics logs (port only, no CSRF)
|
||||
this._port = await this._discoverPortFromDiagnostics();
|
||||
if (this._port) {
|
||||
log.warn(`LS port from diagnostics: ${this._port}, but CSRF token not found — RPC calls may fail with 401`);
|
||||
return true;
|
||||
}
|
||||
|
||||
log.warn('Could not discover LS connection. Use setConnection(port, csrfToken) manually.');
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Whether the bridge is ready (port discovered) */
|
||||
get isReady(): boolean {
|
||||
return this._port !== null;
|
||||
}
|
||||
|
||||
/** The discovered LS port */
|
||||
get port(): number | null {
|
||||
return this._port;
|
||||
}
|
||||
|
||||
/** Whether CSRF token is available */
|
||||
get hasCsrfToken(): boolean {
|
||||
return this._csrfToken !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually set the LS connection parameters.
|
||||
*
|
||||
* Use this when auto-discovery fails (e.g., non-standard install,
|
||||
* or you've discovered the port/token through other means like `lsof`).
|
||||
*
|
||||
* @param port - LS port number
|
||||
* @param csrfToken - CSRF token from LS process CLI args
|
||||
* @param useTls - Whether to use HTTPS (default: false, extension_server uses HTTP)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const ls = new LSBridge(commandBridge);
|
||||
* const ok = await ls.initialize();
|
||||
* if (!ok) {
|
||||
* // Manual fallback: get port and csrf from your own discovery
|
||||
* ls.setConnection(54321, 'abc123-csrf-token');
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
setConnection(port: number, csrfToken: string, useTls: boolean = false): void {
|
||||
this._port = port;
|
||||
this._csrfToken = csrfToken;
|
||||
this._useTls = useTls;
|
||||
log.info(`LS connection set manually: port=${port}, tls=${useTls}, csrf=${csrfToken ? 'provided' : 'empty'}`);
|
||||
}
|
||||
|
||||
// ─── Headless Cascade API ────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Create a new cascade and optionally send a message.
|
||||
* Fully headless — no UI panel opened, no conversation switched.
|
||||
*
|
||||
* @returns cascadeId or null on failure
|
||||
*/
|
||||
async createCascade(options: IHeadlessCascadeOptions): Promise<string | null> {
|
||||
this._ensureReady();
|
||||
|
||||
// Step 1: StartCascade
|
||||
const startResp = await this._rpc('StartCascade', { source: 0 });
|
||||
const cascadeId = startResp?.cascadeId;
|
||||
if (!cascadeId) {
|
||||
log.error('StartCascade returned no cascadeId');
|
||||
return null;
|
||||
}
|
||||
log.info(`Cascade created: ${cascadeId}`);
|
||||
|
||||
// Step 2: SendUserCascadeMessage
|
||||
if (options.text) {
|
||||
await this._sendMessage(cascadeId, options.text, options.model, options.plannerType);
|
||||
log.info(`Message sent to: ${cascadeId}`);
|
||||
}
|
||||
|
||||
return cascadeId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message to an existing cascade.
|
||||
*
|
||||
* @returns true if sent successfully
|
||||
*/
|
||||
async sendMessage(options: ISendMessageOptions): Promise<boolean> {
|
||||
this._ensureReady();
|
||||
await this._sendMessage(options.cascadeId, options.text, options.model);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch the UI to show a specific cascade conversation.
|
||||
*/
|
||||
async focusCascade(cascadeId: string): Promise<void> {
|
||||
this._ensureReady();
|
||||
await this._rpc('SmartFocusConversation', { cascadeId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel a running cascade invocation.
|
||||
*/
|
||||
async cancelCascade(cascadeId: string): Promise<void> {
|
||||
this._ensureReady();
|
||||
await this._rpc('CancelCascadeInvocation', { cascadeId });
|
||||
}
|
||||
|
||||
// ─── Conversation Annotations API ───────────────────────────────
|
||||
|
||||
/**
|
||||
* Native conversation annotations (verified from jetski_cortex.proto).
|
||||
*
|
||||
* ConversationAnnotations protobuf fields:
|
||||
* - title (string) — custom user title, overrides auto-summary
|
||||
* - tags (string[]) — tags/labels
|
||||
* - archived (bool) — archive status
|
||||
* - starred (bool) — pinned/starred
|
||||
* - last_user_view_time (Timestamp)
|
||||
*
|
||||
* @param cascadeId - Conversation ID
|
||||
* @param annotations - Partial annotation fields to set
|
||||
* @param merge - If true, merge with existing annotations (default: true)
|
||||
*/
|
||||
async updateAnnotations(
|
||||
cascadeId: string,
|
||||
annotations: IConversationAnnotations,
|
||||
merge: boolean = true,
|
||||
): Promise<void> {
|
||||
this._ensureReady();
|
||||
|
||||
// Convert camelCase to snake_case for protobuf
|
||||
const proto: Record<string, any> = {};
|
||||
if (annotations.title !== undefined) proto.title = annotations.title;
|
||||
if (annotations.starred !== undefined) proto.starred = annotations.starred;
|
||||
if (annotations.archived !== undefined) proto.archived = annotations.archived;
|
||||
if (annotations.tags !== undefined) proto.tags = annotations.tags;
|
||||
|
||||
await this._rpc('UpdateConversationAnnotations', {
|
||||
cascadeId,
|
||||
annotations: proto,
|
||||
mergeAnnotations: merge,
|
||||
});
|
||||
log.info(`Annotations updated for ${cascadeId.substring(0, 8)}...`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a custom title for a conversation.
|
||||
*
|
||||
* This sets the `title` field in ConversationAnnotations.
|
||||
* When set, this title should be displayed instead of the
|
||||
* auto-generated `summary` from the LLM.
|
||||
*
|
||||
* @param cascadeId - Conversation ID
|
||||
* @param title - Custom title to set
|
||||
*/
|
||||
async setTitle(cascadeId: string, title: string): Promise<void> {
|
||||
await this.updateAnnotations(cascadeId, { title });
|
||||
}
|
||||
|
||||
/**
|
||||
* Star (pin) or unstar a conversation.
|
||||
*
|
||||
* This sets the `starred` field in ConversationAnnotations.
|
||||
*
|
||||
* @param cascadeId - Conversation ID
|
||||
* @param starred - true to star, false to unstar
|
||||
*/
|
||||
async setStar(cascadeId: string, starred: boolean): Promise<void> {
|
||||
await this.updateAnnotations(cascadeId, { starred });
|
||||
}
|
||||
|
||||
// ─── Conversation Read API ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Get details of a specific conversation.
|
||||
*/
|
||||
async getConversation(cascadeId: string): Promise<any> {
|
||||
this._ensureReady();
|
||||
return this._rpc('GetConversation', { cascadeId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all cascade trajectories (conversation list).
|
||||
*/
|
||||
async listCascades(): Promise<any> {
|
||||
this._ensureReady();
|
||||
const resp = await this._rpc('GetAllCascadeTrajectories', {});
|
||||
return resp?.trajectorySummaries ?? {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get trajectory descriptions (lighter than full trajectories).
|
||||
* Returns { trajectories: [...] }.
|
||||
*/
|
||||
async getTrajectoryDescriptions(): Promise<any> {
|
||||
this._ensureReady();
|
||||
return this._rpc('GetUserTrajectoryDescriptions', {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user status (tier, models, etc.)
|
||||
*/
|
||||
async getUserStatus(): Promise<any> {
|
||||
this._ensureReady();
|
||||
return this._rpc('GetUserStatus', {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a raw RPC call to any LS method.
|
||||
* @param method - RPC method name (e.g. 'StartCascade')
|
||||
* @param payload - JSON payload
|
||||
*/
|
||||
async rawRPC(method: string, payload: any): Promise<any> {
|
||||
this._ensureReady();
|
||||
return this._rpc(method, payload);
|
||||
}
|
||||
|
||||
// ─── Internal ────────────────────────────────────────────────────
|
||||
|
||||
private _ensureReady(): void {
|
||||
if (!this._port) {
|
||||
throw new Error('LSBridge not initialized. Call initialize() first.');
|
||||
}
|
||||
}
|
||||
|
||||
private async _sendMessage(
|
||||
cascadeId: string,
|
||||
text: string,
|
||||
model?: ModelId,
|
||||
plannerType?: string,
|
||||
): Promise<void> {
|
||||
const payload: any = {
|
||||
cascadeId,
|
||||
items: [{ chunk: { case: 'text', value: text } }],
|
||||
cascadeConfig: {
|
||||
plannerConfig: {
|
||||
plannerTypeConfig: {
|
||||
case: plannerType || 'conversational',
|
||||
value: {},
|
||||
},
|
||||
requestedModel: {
|
||||
choice: { case: 'model', value: model || Models.GEMINI_FLASH },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
await this._rpc('SendUserCascadeMessage', payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover LS port and CSRF token from the Language Server process.
|
||||
*
|
||||
* VERIFIED 2026-03-01 from Antigravity extension.js source:
|
||||
*
|
||||
* 1. CSRF header is "x-codeium-csrf-token" (NOT x-csrf-token)
|
||||
* 2. CSRF value is --csrf_token from CLI (NOT --extension_server_csrf_token)
|
||||
* 3. ConnectRPC endpoint is on httpsPort (HTTPS) or httpPort (HTTP)
|
||||
* These ports are NOT in CLI args (--random_port flag means random).
|
||||
* We discover them via netstat/PID, excluding extension_server_port.
|
||||
*
|
||||
* Source code proof:
|
||||
* n.header.set("x-codeium-csrf-token", e) // header name
|
||||
* address = `127.0.0.1:${te.httpsPort}` // ConnectRPC address
|
||||
* csrfToken = a = d.randomUUID() → --csrf_token // token source
|
||||
* t.headers["x-codeium-csrf-token"] === this.csrfToken ? ... : 403
|
||||
*
|
||||
* Discovery: 2 phases
|
||||
* Phase 1: Get-CimInstance/ps → PID, --csrf_token, --extension_server_port
|
||||
* Phase 2: netstat → find LISTENING ports for PID, exclude ext_server_port
|
||||
*/
|
||||
private async _discoverFromProcess(): Promise<{ port: number; csrfToken: string; useTls: boolean } | null> {
|
||||
try {
|
||||
const platform = process.platform;
|
||||
|
||||
// Phase 1: find LS process, extract PID, csrf_token, extension_server_port
|
||||
let processInfo = await this._findLSProcess(platform);
|
||||
if (!processInfo) {
|
||||
log.debug('No LS processes found');
|
||||
return null;
|
||||
}
|
||||
|
||||
log.debug(`LS process found: PID=${processInfo.pid}, csrf=present, ext_port=${processInfo.extPort}`);
|
||||
|
||||
// Phase 2: find actual ConnectRPC port via netstat
|
||||
const connectPort = await this._findConnectPort(platform, processInfo.pid, processInfo.extPort);
|
||||
if (!connectPort) {
|
||||
log.debug('Could not find ConnectRPC port via netstat, trying extension_server_port as fallback');
|
||||
// Fallback: try extension_server_port with HTTP
|
||||
if (processInfo.extPort) {
|
||||
return { port: processInfo.extPort, csrfToken: processInfo.csrfToken, useTls: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
port: connectPort.port,
|
||||
csrfToken: processInfo.csrfToken,
|
||||
useTls: connectPort.tls,
|
||||
};
|
||||
|
||||
} catch (err) {
|
||||
log.debug('Process discovery failed', err);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase 1: Find the LS process for this workspace.
|
||||
*/
|
||||
private async _findLSProcess(
|
||||
platform: string,
|
||||
): Promise<{ pid: number; csrfToken: string; extPort: number } | null> {
|
||||
const { exec } = require('child_process');
|
||||
const { promisify } = require('util');
|
||||
const execAsync = promisify(exec);
|
||||
let output: string;
|
||||
|
||||
if (platform === 'win32') {
|
||||
// Use -EncodedCommand to avoid all PowerShell escaping issues with $_ and quotes
|
||||
const psScript = "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -match 'language_server' -and $_.CommandLine -match 'csrf_token' } | ForEach-Object { $_.ProcessId.ToString() + '|' + $_.CommandLine }";
|
||||
const encoded = Buffer.from(psScript, 'utf16le').toString('base64');
|
||||
const result = await execAsync(
|
||||
`powershell.exe -NoProfile -EncodedCommand ${encoded}`,
|
||||
{ encoding: 'utf8', timeout: 10000, windowsHide: true },
|
||||
);
|
||||
output = result.stdout;
|
||||
} else {
|
||||
const result = await execAsync(
|
||||
'ps -eo pid,args 2>/dev/null | grep language_server | grep csrf_token | grep -v grep',
|
||||
{ encoding: 'utf8', timeout: 5000 },
|
||||
);
|
||||
output = result.stdout;
|
||||
}
|
||||
|
||||
const lines = output.split('\n').filter((l: string) => l.trim().length > 0);
|
||||
if (lines.length === 0) return null;
|
||||
|
||||
const workspaceHint = this._getWorkspaceHint();
|
||||
let bestLine: string | null = null;
|
||||
|
||||
if (workspaceHint) {
|
||||
for (const line of lines) {
|
||||
if (line.includes(workspaceHint)) {
|
||||
bestLine = line;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!bestLine) bestLine = lines[0];
|
||||
|
||||
// Extract PID (first field before | on Windows, first token on Unix)
|
||||
let pid: number;
|
||||
if (platform === 'win32') {
|
||||
pid = parseInt(bestLine.split('|')[0].trim(), 10);
|
||||
} else {
|
||||
pid = parseInt(bestLine.trim().split(/\s+/)[0], 10);
|
||||
}
|
||||
|
||||
const csrfToken = this._extractArg(bestLine, 'csrf_token');
|
||||
const extPortStr = this._extractArg(bestLine, 'extension_server_port');
|
||||
const extPort = extPortStr ? parseInt(extPortStr, 10) : 0;
|
||||
|
||||
if (!csrfToken || isNaN(pid)) return null;
|
||||
|
||||
return { pid, csrfToken, extPort };
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase 2: Find ConnectRPC port via netstat.
|
||||
*
|
||||
* The LS process listens on multiple ports:
|
||||
* - httpsPort (HTTPS, ConnectRPC) ← this is what we want
|
||||
* - httpPort (HTTP, ConnectRPC) ← also works
|
||||
* - lspPort (LSP JSON-RPC)
|
||||
* - extension_server_port is separate (for Extension Host IPC)
|
||||
*
|
||||
* We find all LISTENING ports for the LS PID, exclude ext_server_port,
|
||||
* then try HTTPS first (preferred), fall back to HTTP.
|
||||
*/
|
||||
private async _findConnectPort(
|
||||
platform: string,
|
||||
pid: number,
|
||||
extPort: number,
|
||||
): Promise<{ port: number; tls: boolean } | null> {
|
||||
try {
|
||||
const { exec } = require('child_process');
|
||||
const { promisify } = require('util');
|
||||
const execAsync = promisify(exec);
|
||||
let output: string;
|
||||
|
||||
if (platform === 'win32') {
|
||||
const result = await execAsync(
|
||||
`netstat -aon | findstr "LISTENING" | findstr "${pid}"`,
|
||||
{ encoding: 'utf8', timeout: 5000, windowsHide: true },
|
||||
);
|
||||
output = result.stdout;
|
||||
} else {
|
||||
const result = await execAsync(
|
||||
`ss -tlnp 2>/dev/null | grep "pid=${pid}" || netstat -tlnp 2>/dev/null | grep "${pid}"`,
|
||||
{ encoding: 'utf8', timeout: 5000 },
|
||||
);
|
||||
output = result.stdout;
|
||||
}
|
||||
|
||||
// Extract all listening ports for this PID
|
||||
const portMatches = output.matchAll(/127\.0\.0\.1:(\d+)/g);
|
||||
const ports: number[] = [];
|
||||
for (const m of portMatches) {
|
||||
const p = parseInt(m[1], 10);
|
||||
// Exclude extension_server_port
|
||||
if (p !== extPort && !ports.includes(p)) {
|
||||
ports.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
if (ports.length === 0) return null;
|
||||
|
||||
log.debug(`LS ports (excl ext ${extPort}): ${ports.join(', ')}`);
|
||||
|
||||
// Try to identify httpsPort vs httpPort by probing
|
||||
// Strategy: try HTTPS first on each port (httpsPort is preferred)
|
||||
for (const port of ports) {
|
||||
const tls = await this._probePort(port, true);
|
||||
if (tls) return { port, tls: true };
|
||||
}
|
||||
|
||||
// Fallback: try HTTP
|
||||
for (const port of ports) {
|
||||
const http = await this._probePort(port, false);
|
||||
if (http) return { port, tls: false };
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
log.debug('netstat port discovery failed', err);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick probe: check if a port accepts ConnectRPC requests.
|
||||
* Returns true if the port responds (even with error) on the given protocol.
|
||||
*/
|
||||
private _probePort(port: number, useTls: boolean): Promise<boolean> {
|
||||
const mod = useTls ? require('https') : require('http');
|
||||
const proto = useTls ? 'https' : 'http';
|
||||
return new Promise((resolve) => {
|
||||
const req = mod.request(`${proto}://127.0.0.1:${port}/exa.language_server_pb.LanguageServerService/GetUserStatus`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Content-Length': 2 },
|
||||
rejectUnauthorized: false,
|
||||
timeout: 2000,
|
||||
}, (res: any) => {
|
||||
// 401 = correct endpoint, just missing CSRF (expected)
|
||||
// 200 = also correct (unlikely without CSRF but possible)
|
||||
resolve(res.statusCode === 401 || res.statusCode === 200);
|
||||
});
|
||||
req.on('error', () => resolve(false));
|
||||
req.on('timeout', () => { req.destroy(); resolve(false); });
|
||||
req.write('{}');
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a workspace hint string used to match the correct LS process.
|
||||
*
|
||||
* The LS process has --workspace_id like:
|
||||
* file_d_3A_programming_better_antigravity
|
||||
* which is an encoded version of the workspace URI.
|
||||
*/
|
||||
private _getWorkspaceHint(): string {
|
||||
try {
|
||||
const vscode = require('vscode');
|
||||
const folders = vscode.workspace?.workspaceFolders;
|
||||
if (folders && folders.length > 0) {
|
||||
// Convert workspace path to LS workspace_id format
|
||||
// e.g., "d:\programming\better-antigravity" -> "better_antigravity"
|
||||
// (LS uses underscored path segments)
|
||||
const folder = folders[0].uri.fsPath;
|
||||
const parts = folder.replace(/\\/g, '/').split('/');
|
||||
// Use last 2-3 segments for matching
|
||||
return parts.slice(-2).join('_').replace(/[-.\s]/g, '_').toLowerCase();
|
||||
}
|
||||
} catch {
|
||||
// vscode not available (e.g., testing)
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a CLI argument value from a command-line string.
|
||||
* Supports both --key=value and --key value formats.
|
||||
*/
|
||||
private _extractArg(cmdLine: string, argName: string): string | null {
|
||||
// --argName=value
|
||||
const eqMatch = cmdLine.match(new RegExp(`--${argName}=([^\\s"]+)`));
|
||||
if (eqMatch) return eqMatch[1];
|
||||
|
||||
// --argName value
|
||||
const spaceMatch = cmdLine.match(new RegExp(`--${argName}\\s+([^\\s"]+)`));
|
||||
if (spaceMatch) return spaceMatch[1];
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback: discover port from getDiagnostics console logs.
|
||||
* NOTE: This does NOT discover the CSRF token.
|
||||
* In recent Antigravity versions, the port URL may no longer appear in logs.
|
||||
*/
|
||||
private async _discoverPortFromDiagnostics(): Promise<number | null> {
|
||||
try {
|
||||
const raw = await this._executeCommand<string>('antigravity.getDiagnostics');
|
||||
if (!raw || typeof raw !== 'string') return null;
|
||||
const diag = JSON.parse(raw);
|
||||
|
||||
const logs: string = diag.agentWindowConsoleLogs || '';
|
||||
|
||||
// Pattern: 127.0.0.1:{port}/exa.language_server_pb
|
||||
const m1 = logs.match(/127\.0\.0\.1:(\d+)\/exa\.language_server_pb/);
|
||||
if (m1) return parseInt(m1[1], 10);
|
||||
|
||||
// Fallback: any 127.0.0.1:{port} in HTTPS context
|
||||
const m2 = logs.match(/https?:\/\/127\.0\.0\.1:(\d+)/);
|
||||
if (m2) return parseInt(m2[1], 10);
|
||||
|
||||
// Check mainThreadLogs for port info
|
||||
if (diag.mainThreadLogs) {
|
||||
const mainLogs = typeof diag.mainThreadLogs === 'string'
|
||||
? diag.mainThreadLogs
|
||||
: JSON.stringify(diag.mainThreadLogs);
|
||||
const m3 = mainLogs.match(/127\.0\.0\.1:(\d+)/);
|
||||
if (m3) return parseInt(m3[1], 10);
|
||||
}
|
||||
} catch (err) {
|
||||
log.error('Failed to discover LS port from diagnostics', err);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make an authenticated RPC call to the Language Server.
|
||||
* Sends x-csrf-token header when available.
|
||||
*
|
||||
* VERIFIED 2026-03-01:
|
||||
* - extension_server_port uses plain HTTP (no TLS)
|
||||
* - Main LS port (--random_port) uses HTTPS with self-signed cert
|
||||
*/
|
||||
private async _rpc(method: string, payload: any): Promise<any> {
|
||||
const httpModule = this._useTls ? require('https') : require('http');
|
||||
const protocol = this._useTls ? 'https' : 'http';
|
||||
const url = `${protocol}://127.0.0.1:${this._port}/exa.language_server_pb.LanguageServerService/${method}`;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const body = JSON.stringify(payload);
|
||||
const headers: Record<string, string | number> = {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
};
|
||||
|
||||
// CSRF header: "x-codeium-csrf-token" (verified from extension.js source)
|
||||
if (this._csrfToken) {
|
||||
headers['x-codeium-csrf-token'] = this._csrfToken;
|
||||
}
|
||||
|
||||
const reqOptions: any = {
|
||||
method: 'POST',
|
||||
headers,
|
||||
};
|
||||
|
||||
// Self-signed TLS when using HTTPS
|
||||
if (this._useTls) {
|
||||
reqOptions.rejectUnauthorized = false;
|
||||
}
|
||||
|
||||
const req = httpModule.request(url, reqOptions, (res: any) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk: string) => { data += chunk; });
|
||||
res.on('end', () => {
|
||||
if (res.statusCode === 200) {
|
||||
try { resolve(JSON.parse(data)); }
|
||||
catch { resolve(data); }
|
||||
} else {
|
||||
const hint = res.statusCode === 401
|
||||
? ' (CSRF token may be invalid or missing -- try setConnection() with the correct token)'
|
||||
: '';
|
||||
reject(new Error(`LS ${method}: ${res.statusCode} -- ${data.substring(0, 200)}${hint}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', (err: Error) => reject(err));
|
||||
req.write(body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
}
|
||||
518
antigravity-sdk-main/src/transport/state-bridge.ts
Normal file
518
antigravity-sdk-main/src/transport/state-bridge.ts
Normal file
@@ -0,0 +1,518 @@
|
||||
/**
|
||||
* State Bridge — reads Antigravity's USS state from the SQLite database.
|
||||
*
|
||||
* Antigravity stores settings, conversation metadata, and agent preferences
|
||||
* in `state.vscdb` (SQLite). This bridge provides read-only access to that data.
|
||||
*
|
||||
* VERIFIED against live state.vscdb on 2026-02-28.
|
||||
*
|
||||
* @module transport/state-bridge
|
||||
*/
|
||||
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import { IDisposable } from '../core/disposable';
|
||||
import { StateReadError } from '../core/errors';
|
||||
import { Logger } from '../core/logger';
|
||||
import type {
|
||||
IAgentPreferences,
|
||||
TerminalExecutionPolicy,
|
||||
ArtifactReviewPolicy,
|
||||
} from '../core/types';
|
||||
|
||||
const log = new Logger('StateBridge');
|
||||
|
||||
/**
|
||||
* USS (Unified State Sync) keys in state.vscdb.
|
||||
*
|
||||
* VERIFIED: All keys listed below were confirmed to exist
|
||||
* in a live Antigravity v1.107.0 installation on 2026-02-28.
|
||||
* Values are Base64-encoded protobuf unless noted otherwise.
|
||||
*/
|
||||
export const USSKeys = {
|
||||
/** Agent preferences — terminal policy, review policy, secure mode, etc. (1020 bytes) */
|
||||
AGENT_PREFERENCES: 'antigravityUnifiedStateSync.agentPreferences',
|
||||
|
||||
/** Conversation/trajectory summaries — titles, timestamps, workspace URIs (74KB+) */
|
||||
TRAJECTORY_SUMMARIES: 'antigravityUnifiedStateSync.trajectorySummaries',
|
||||
|
||||
/** Agent manager window state (192 bytes) */
|
||||
AGENT_MANAGER_WINDOW: 'antigravityUnifiedStateSync.agentManagerWindow',
|
||||
|
||||
/** Enterprise override store (56 bytes) */
|
||||
OVERRIDE_STORE: 'antigravityUnifiedStateSync.overrideStore',
|
||||
|
||||
/** Model preferences — selected model, sentinel key */
|
||||
MODEL_PREFERENCES: 'antigravityUnifiedStateSync.modelPreferences',
|
||||
|
||||
/** Artifact review state (1204 bytes) */
|
||||
ARTIFACT_REVIEW: 'antigravityUnifiedStateSync.artifactReview',
|
||||
|
||||
/** Browser preferences (380 bytes) */
|
||||
BROWSER_PREFERENCES: 'antigravityUnifiedStateSync.browserPreferences',
|
||||
|
||||
/** Editor preferences (108 bytes) */
|
||||
EDITOR_PREFERENCES: 'antigravityUnifiedStateSync.editorPreferences',
|
||||
|
||||
/** Tab preferences (404 bytes) */
|
||||
TAB_PREFERENCES: 'antigravityUnifiedStateSync.tabPreferences',
|
||||
|
||||
/** Window preferences (44 bytes) */
|
||||
WINDOW_PREFERENCES: 'antigravityUnifiedStateSync.windowPreferences',
|
||||
|
||||
/** Scratch/playground workspaces (268 bytes) */
|
||||
SCRATCH_WORKSPACES: 'antigravityUnifiedStateSync.scratchWorkspaces',
|
||||
|
||||
/** Sidebar workspaces — recent workspace list (5604 bytes) */
|
||||
SIDEBAR_WORKSPACES: 'antigravityUnifiedStateSync.sidebarWorkspaces',
|
||||
|
||||
/** User status info (5196 bytes) */
|
||||
USER_STATUS: 'antigravityUnifiedStateSync.userStatus',
|
||||
|
||||
/** Model credits/usage info */
|
||||
MODEL_CREDITS: 'antigravityUnifiedStateSync.modelCredits',
|
||||
|
||||
/** Onboarding state (140 bytes) */
|
||||
ONBOARDING: 'antigravityUnifiedStateSync.onboarding',
|
||||
|
||||
/** Seen NUX (new user experience) IDs (76 bytes) */
|
||||
SEEN_NUX_IDS: 'antigravityUnifiedStateSync.seenNuxIds',
|
||||
|
||||
// ⚠️ Jetski-specific state (separate sync namespace)
|
||||
/** Agent manager initialization state — contains auth tokens, workspace map (5144 bytes) */
|
||||
AGENT_MANAGER_INIT: 'jetskiStateSync.agentManagerInitState',
|
||||
|
||||
// ⚠️ Non-USS but relevant keys
|
||||
/** All user settings — JSON format */
|
||||
ALL_USER_SETTINGS: 'antigravityUserSettings.allUserSettings',
|
||||
|
||||
/** Allowed model configs for commands */
|
||||
ALLOWED_COMMAND_MODEL_CONFIGS: 'antigravity_allowed_command_model_configs',
|
||||
|
||||
/** Chat session store index (JSON: {"version":1,"entries":{}}) */
|
||||
CHAT_SESSION_INDEX: 'chat.ChatSessionStore.index',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Keys that contain sensitive data and MUST NOT be exposed through the SDK.
|
||||
*
|
||||
* VERIFIED 2026-02-28:
|
||||
* - oauthToken: OAuth access token (732 bytes)
|
||||
* - agentManagerInitState: Contains LIVE ya29.* access token + g1//* refresh token!
|
||||
* - antigravityAuthStatus: Auth status
|
||||
*/
|
||||
const SENSITIVE_KEYS = new Set([
|
||||
'antigravityUnifiedStateSync.oauthToken',
|
||||
'jetskiStateSync.agentManagerInitState',
|
||||
'antigravityAuthStatus',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Protobuf sentinel keys found in agentPreferences.
|
||||
*
|
||||
* ALL 16 sentinel keys verified from live state.vscdb on 2026-02-28.
|
||||
* Each sentinel key string is followed by a small Base64 value encoding
|
||||
* a protobuf varint (the actual preference value).
|
||||
*/
|
||||
const SENTINEL_KEYS = {
|
||||
PLANNING_MODE: 'planningModeSentinelKey',
|
||||
ARTIFACT_REVIEW_POLICY: 'artifactReviewPolicySentinelKey',
|
||||
TERMINAL_AUTO_EXECUTION_POLICY: 'terminalAutoExecutionPolicySentinelKey',
|
||||
TERMINAL_ALLOWED_COMMANDS: 'terminalAllowedCommandsSentinelKey',
|
||||
TERMINAL_DENIED_COMMANDS: 'terminalDeniedCommandsSentinelKey',
|
||||
ALLOW_NON_WORKSPACE_FILES: 'allowAgentAccessNonWorkspaceFilesSentinelKey',
|
||||
ALLOW_GITIGNORE_ACCESS: 'allowCascadeAccessGitignoreFilesSentinelKey',
|
||||
SECURE_MODE: 'secureModeSentinelKey',
|
||||
EXPLAIN_FIX_IN_CONVO: 'explainAndFixInCurrentConversationSentinelKey',
|
||||
AUTO_CONTINUE_ON_MAX: 'autoContinueOnMaxGeneratorInvocationsSentinelKey',
|
||||
DISABLE_AUTO_OPEN_EDITED: 'disableAutoOpenEditedFilesSentinelKey',
|
||||
ENABLE_SOUNDS: 'enableSoundsForSpecialEventsSentinelKey',
|
||||
DISABLE_AUTO_FIX_LINTS: 'disableCascadeAutoFixLintsSentinelKey',
|
||||
ENABLE_SHELL_INTEGRATION: 'enableShellIntegrationSentinelKey',
|
||||
SANDBOX_ALLOW_NETWORK: 'sandboxAllowNetworkSentinelKey',
|
||||
ENABLE_TERMINAL_SANDBOX: 'enableTerminalSandboxSentinelKey',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Reads Antigravity's internal state from the SQLite database.
|
||||
*
|
||||
* Uses **sql.js** (pure JavaScript SQLite, compiled to WASM) which is
|
||||
* verified to work in Antigravity's Extension Host (unlike better-sqlite3
|
||||
* which fails due to ABI mismatch with Electron v22.21.1 / ABI v140).
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const bridge = new StateBridge();
|
||||
* await bridge.initialize();
|
||||
*
|
||||
* const prefs = await bridge.getAgentPreferences();
|
||||
* console.log(prefs.terminalExecutionPolicy);
|
||||
* ```
|
||||
*/
|
||||
export class StateBridge implements IDisposable {
|
||||
private _dbPath: string | null = null;
|
||||
private _db: any = null; // sql.js Database instance
|
||||
private _disposed = false;
|
||||
|
||||
/**
|
||||
* Initialize the state bridge by locating and opening state database.
|
||||
*
|
||||
* @throws {StateReadError} If the database cannot be found
|
||||
*/
|
||||
async initialize(): Promise<void> {
|
||||
const dbPath = this._findStateDb();
|
||||
|
||||
if (!dbPath) {
|
||||
throw new StateReadError('state.vscdb', 'Could not locate Antigravity state database');
|
||||
}
|
||||
|
||||
this._dbPath = dbPath;
|
||||
|
||||
// Open with sql.js (pure JS — verified working in Extension Host)
|
||||
try {
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
// Try to load sql.js from multiple locations:
|
||||
// 1. Adjacent sql-wasm.js (for VSIX bundles where consumer copies it to dist/)
|
||||
// 2. Standard require('sql.js') (for npm install / dev setups)
|
||||
let initSqlJs: any;
|
||||
const localSqlJs = path.join(__dirname, 'sql-wasm.js');
|
||||
if (fs.existsSync(localSqlJs)) {
|
||||
initSqlJs = require(localSqlJs);
|
||||
} else {
|
||||
initSqlJs = require('sql.js');
|
||||
}
|
||||
|
||||
// Auto-locate sql-wasm.wasm — try multiple paths so devs
|
||||
// don't need to manually copy anything after `npm install`
|
||||
const candidates = [
|
||||
// 1. Adjacent to this file (if wasm was bundled/copied to dist/)
|
||||
path.join(__dirname, 'sql-wasm.wasm'),
|
||||
// 2. sql.js package dist/ (standard npm install)
|
||||
path.resolve(__dirname, '..', 'node_modules', 'sql.js', 'dist', 'sql-wasm.wasm'),
|
||||
// 3. Hoisted node_modules (monorepo / npm workspaces)
|
||||
path.resolve(__dirname, '..', '..', 'node_modules', 'sql.js', 'dist', 'sql-wasm.wasm'),
|
||||
// 4. Walk up to find it (deep hoisting)
|
||||
path.resolve(__dirname, '..', '..', '..', 'node_modules', 'sql.js', 'dist', 'sql-wasm.wasm'),
|
||||
];
|
||||
|
||||
// Try require.resolve — works in all layouts
|
||||
try {
|
||||
const sqlJsMain = require.resolve('sql.js');
|
||||
candidates.unshift(path.join(path.dirname(sqlJsMain), 'sql-wasm.wasm'));
|
||||
} catch {
|
||||
// sql.js might not have a resolvable main in all setups
|
||||
}
|
||||
|
||||
let wasmPath: string | null = null;
|
||||
for (const p of candidates) {
|
||||
if (fs.existsSync(p)) {
|
||||
wasmPath = p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!wasmPath) {
|
||||
throw new Error('sql-wasm.wasm not found in any expected location');
|
||||
}
|
||||
|
||||
const SQL = await initSqlJs({
|
||||
locateFile: () => wasmPath!,
|
||||
});
|
||||
const fileBuffer = fs.readFileSync(dbPath);
|
||||
this._db = new SQL.Database(fileBuffer);
|
||||
log.info(`State database opened via sql.js: ${dbPath}`);
|
||||
} catch (error) {
|
||||
log.warn('sql.js not available, will use child_process fallback', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a raw value from the state database.
|
||||
*
|
||||
* @param key - The SQLite key to read
|
||||
* @returns The raw string value, or null if not found
|
||||
* @throws {StateReadError} If the key is sensitive or read fails
|
||||
*/
|
||||
async getRawValue(key: string): Promise<string | null> {
|
||||
if (this._disposed) {
|
||||
throw new StateReadError(key, 'StateBridge has been disposed');
|
||||
}
|
||||
|
||||
if (!this._dbPath) {
|
||||
throw new StateReadError(key, 'StateBridge not initialized');
|
||||
}
|
||||
|
||||
// Block access to sensitive keys
|
||||
if (SENSITIVE_KEYS.has(key)) {
|
||||
throw new StateReadError(key, 'Access to sensitive keys is blocked by the SDK for security');
|
||||
}
|
||||
|
||||
try {
|
||||
if (this._db) {
|
||||
return this._querySqlJs(key);
|
||||
}
|
||||
return await this._queryChildProcess(key);
|
||||
} catch (error) {
|
||||
if (error instanceof StateReadError) throw error;
|
||||
const msg = error instanceof Error ? error.message : String(error);
|
||||
throw new StateReadError(key, msg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get agent preferences from USS.
|
||||
*
|
||||
* @returns Parsed agent preferences
|
||||
*/
|
||||
async getAgentPreferences(): Promise<IAgentPreferences> {
|
||||
const raw = await this.getRawValue(USSKeys.AGENT_PREFERENCES);
|
||||
|
||||
if (!raw) {
|
||||
log.warn('No agent preferences found, returning defaults');
|
||||
return this._defaultPreferences();
|
||||
}
|
||||
|
||||
try {
|
||||
return this._parseAgentPreferences(raw);
|
||||
} catch (error) {
|
||||
log.error('Failed to parse preferences, returning defaults', error);
|
||||
return this._defaultPreferences();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all stored USS keys from the state database.
|
||||
*
|
||||
* @returns List of key names related to Antigravity (excludes sensitive keys)
|
||||
*/
|
||||
async getAntigravityKeys(): Promise<string[]> {
|
||||
if (!this._dbPath) {
|
||||
throw new StateReadError('*', 'StateBridge not initialized');
|
||||
}
|
||||
|
||||
let keys: string[];
|
||||
|
||||
if (this._db) {
|
||||
const result = this._db.exec(
|
||||
"SELECT key FROM ItemTable WHERE key LIKE '%antigravity%' OR key LIKE '%jetskiStateSync%' OR key LIKE 'chat.%'",
|
||||
);
|
||||
keys = result.length > 0 ? result[0].values.map((r: any[]) => r[0] as string) : [];
|
||||
} else {
|
||||
const result = await this._queryChildProcess('*');
|
||||
keys = result ? result.split('\n').map((l: string) => l.trim()).filter(Boolean) : [];
|
||||
}
|
||||
|
||||
// Filter out sensitive keys
|
||||
return keys.filter((k) => !SENSITIVE_KEYS.has(k));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query using sql.js (in-process, pure JS).
|
||||
*/
|
||||
private _querySqlJs(key: string): string | null {
|
||||
const stmt = this._db.prepare('SELECT value FROM ItemTable WHERE key = $key');
|
||||
stmt.bind({ $key: key });
|
||||
if (stmt.step()) {
|
||||
const row = stmt.getAsObject();
|
||||
stmt.free();
|
||||
return (row.value as string) ?? null;
|
||||
}
|
||||
stmt.free();
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Query using child_process sqlite3 CLI (fallback).
|
||||
*/
|
||||
private async _queryChildProcess(key: string): Promise<string | null> {
|
||||
const { exec } = require('child_process');
|
||||
const { promisify } = require('util');
|
||||
const execAsync = promisify(exec);
|
||||
const sql =
|
||||
key === '*'
|
||||
? "SELECT key FROM ItemTable WHERE key LIKE '%antigravity%' OR key LIKE '%jetskiStateSync%'"
|
||||
: `SELECT value FROM ItemTable WHERE key = '${key.replace(/'/g, "''")}'`;
|
||||
|
||||
try {
|
||||
const { stdout } = await execAsync(`sqlite3 "${this._dbPath}" "${sql}"`, {
|
||||
encoding: 'utf8',
|
||||
timeout: 5000,
|
||||
});
|
||||
return stdout.trim() || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Locate the state.vscdb file across platforms.
|
||||
*/
|
||||
private _findStateDb(): string | null {
|
||||
const candidates: string[] = [];
|
||||
|
||||
// Windows (VERIFIED: this is the correct path)
|
||||
const appData = process.env.APPDATA;
|
||||
if (appData) {
|
||||
candidates.push(path.join(appData, 'Antigravity', 'User', 'globalStorage', 'state.vscdb'));
|
||||
}
|
||||
|
||||
// macOS
|
||||
const home = process.env.HOME;
|
||||
if (home) {
|
||||
candidates.push(
|
||||
path.join(
|
||||
home,
|
||||
'Library',
|
||||
'Application Support',
|
||||
'Antigravity',
|
||||
'User',
|
||||
'globalStorage',
|
||||
'state.vscdb',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Linux
|
||||
if (home) {
|
||||
candidates.push(
|
||||
path.join(home, '.config', 'Antigravity', 'User', 'globalStorage', 'state.vscdb'),
|
||||
);
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse agent preferences from Base64(Protobuf).
|
||||
*
|
||||
* The protobuf structure uses "sentinel keys" as string fields:
|
||||
* - `planningModeSentinelKey` → nested message with Base64(varint)
|
||||
* - `terminalAutoExecutionPolicySentinelKey` → nested message with Base64(varint)
|
||||
* - `artifactReviewPolicySentinelKey` → nested message with Base64(varint)
|
||||
*
|
||||
* Each sentinel value is itself a small Base64 string (e.g., "EAM=" = varint 3 = EAGER).
|
||||
*/
|
||||
private _parseAgentPreferences(raw: string): IAgentPreferences {
|
||||
const buffer = Buffer.from(raw, 'base64');
|
||||
const text = buffer.toString('utf8');
|
||||
|
||||
// Extract all sentinel values
|
||||
const terminalPolicy = this._extractSentinelValue(text, SENTINEL_KEYS.TERMINAL_AUTO_EXECUTION_POLICY);
|
||||
const artifactPolicy = this._extractSentinelValue(text, SENTINEL_KEYS.ARTIFACT_REVIEW_POLICY);
|
||||
const planningMode = this._extractSentinelValue(text, SENTINEL_KEYS.PLANNING_MODE);
|
||||
const secureMode = this._extractSentinelValue(text, SENTINEL_KEYS.SECURE_MODE);
|
||||
const terminalSandbox = this._extractSentinelValue(text, SENTINEL_KEYS.ENABLE_TERMINAL_SANDBOX);
|
||||
const sandboxNetwork = this._extractSentinelValue(text, SENTINEL_KEYS.SANDBOX_ALLOW_NETWORK);
|
||||
const shellIntegration = this._extractSentinelValue(text, SENTINEL_KEYS.ENABLE_SHELL_INTEGRATION);
|
||||
const nonWorkspaceFiles = this._extractSentinelValue(text, SENTINEL_KEYS.ALLOW_NON_WORKSPACE_FILES);
|
||||
const gitignoreAccess = this._extractSentinelValue(text, SENTINEL_KEYS.ALLOW_GITIGNORE_ACCESS);
|
||||
const explainFix = this._extractSentinelValue(text, SENTINEL_KEYS.EXPLAIN_FIX_IN_CONVO);
|
||||
const autoContinue = this._extractSentinelValue(text, SENTINEL_KEYS.AUTO_CONTINUE_ON_MAX);
|
||||
const disableAutoOpen = this._extractSentinelValue(text, SENTINEL_KEYS.DISABLE_AUTO_OPEN_EDITED);
|
||||
const enableSounds = this._extractSentinelValue(text, SENTINEL_KEYS.ENABLE_SOUNDS);
|
||||
const disableAutoFix = this._extractSentinelValue(text, SENTINEL_KEYS.DISABLE_AUTO_FIX_LINTS);
|
||||
|
||||
return {
|
||||
terminalExecutionPolicy: (terminalPolicy ?? 1) as TerminalExecutionPolicy,
|
||||
artifactReviewPolicy: (artifactPolicy ?? 1) as ArtifactReviewPolicy,
|
||||
planningMode: planningMode ?? 0,
|
||||
secureModeEnabled: (secureMode ?? 0) === 1,
|
||||
terminalSandboxEnabled: (terminalSandbox ?? 0) === 1,
|
||||
sandboxAllowNetwork: (sandboxNetwork ?? 0) === 1,
|
||||
shellIntegrationEnabled: (shellIntegration ?? 1) === 1,
|
||||
allowNonWorkspaceFiles: (nonWorkspaceFiles ?? 0) === 1,
|
||||
allowGitignoreAccess: (gitignoreAccess ?? 0) === 1,
|
||||
explainFixInCurrentConvo: (explainFix ?? 0) === 1,
|
||||
autoContinueOnMax: autoContinue ?? 0,
|
||||
disableAutoOpenEdited: (disableAutoOpen ?? 0) === 1,
|
||||
enableSounds: (enableSounds ?? 0) === 1,
|
||||
disableAutoFixLints: (disableAutoFix ?? 0) === 1,
|
||||
allowedCommands: [],
|
||||
deniedCommands: [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a varint value from a protobuf sentinel key.
|
||||
*
|
||||
* The structure is: sentinel_key_string followed by a small
|
||||
* Base64 value like "EAM=" (which decodes to a protobuf varint).
|
||||
*
|
||||
* Known mappings:
|
||||
* - "CAE=" → field 1, value 1 (OFF / ALWAYS)
|
||||
* - "EAI=" → field 2, value 2 (AUTO / TURBO)
|
||||
* - "EAM=" → field 2, value 3 (EAGER / AUTO)
|
||||
*/
|
||||
private _extractSentinelValue(text: string, sentinelKey: string): number | null {
|
||||
const idx = text.indexOf(sentinelKey);
|
||||
if (idx === -1) return null;
|
||||
|
||||
// After the sentinel key, look for a small Base64 fragment
|
||||
const after = text.substring(idx + sentinelKey.length, idx + sentinelKey.length + 30);
|
||||
|
||||
// Match a Base64 chunk (typically 4-8 chars ending with =)
|
||||
const b64Match = after.match(/([A-Za-z0-9+/]{2,8}={0,2})/);
|
||||
if (!b64Match) return null;
|
||||
|
||||
try {
|
||||
const decoded = Buffer.from(b64Match[1], 'base64');
|
||||
// Protobuf varint: last byte of the value
|
||||
// For simple single-byte varints, the value is in the lower 7 bits
|
||||
if (decoded.length >= 2) {
|
||||
// The first byte is (field_number << 3 | wire_type)
|
||||
// The second byte is the actual value
|
||||
return decoded[1];
|
||||
} else if (decoded.length === 1) {
|
||||
return decoded[0];
|
||||
}
|
||||
} catch {
|
||||
// Not valid base64
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private _defaultPreferences(): IAgentPreferences {
|
||||
return {
|
||||
terminalExecutionPolicy: 1 as TerminalExecutionPolicy, // OFF
|
||||
artifactReviewPolicy: 1 as ArtifactReviewPolicy, // ALWAYS
|
||||
planningMode: 0,
|
||||
secureModeEnabled: false,
|
||||
terminalSandboxEnabled: false,
|
||||
sandboxAllowNetwork: false,
|
||||
shellIntegrationEnabled: true,
|
||||
allowNonWorkspaceFiles: false,
|
||||
allowGitignoreAccess: false,
|
||||
explainFixInCurrentConvo: false,
|
||||
autoContinueOnMax: 0,
|
||||
disableAutoOpenEdited: false,
|
||||
enableSounds: false,
|
||||
disableAutoFixLints: false,
|
||||
allowedCommands: [],
|
||||
deniedCommands: [],
|
||||
};
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this._disposed = true;
|
||||
|
||||
if (this._db) {
|
||||
try {
|
||||
this._db.close();
|
||||
} catch {
|
||||
// Ignore close errors
|
||||
}
|
||||
this._db = null;
|
||||
}
|
||||
|
||||
this._dbPath = null;
|
||||
}
|
||||
}
|
||||
34
antigravity-sdk-main/tsconfig.json
Normal file
34
antigravity-sdk-main/tsconfig.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"ES2020"
|
||||
],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "node",
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"src/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"src/**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist",
|
||||
"docs-site"
|
||||
]
|
||||
}
|
||||
12
antigravity-sdk-main/tsup.config.ts
Normal file
12
antigravity-sdk-main/tsup.config.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from 'tsup';
|
||||
|
||||
export default defineConfig({
|
||||
entry: ['src/index.ts'],
|
||||
format: ['cjs'],
|
||||
dts: true,
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
external: ['vscode'],
|
||||
splitting: false,
|
||||
treeshake: true,
|
||||
});
|
||||
@@ -1,6 +1,11 @@
|
||||
# 2026-03-08 Devlog — Bridge 프로토콜 수정
|
||||
# 2026-03-08 Devlog — Bridge 프로토콜 수정 + 딥 디버깅
|
||||
|
||||
| # | 시간 | 작업 | 커밋 | 상태 |
|
||||
|---|------|------|------|------|
|
||||
| 1 | 01:00 | Extension↔Bot 프로토콜 불일치 3건 수정 + sql-wasm 번들링 | `e4dc1b1` | 🔧 |
|
||||
| 2 | 01:45~02:25 | Discord Bridge 디버깅: step 구조 파악, 승인 버튼, AI 텍스트 릴레이 | `0c3d6cd` | ✅ |
|
||||
| 3 | 05:30 | 모든 WAITING step relay 구현 + Step type 전체 매핑 (775 steps, 17 types) | - | ✅ |
|
||||
| 4 | 06:10 | 채널 등록 자동화 (writeRegistration) + Bot 파이프라인 검증 | - | ✅ |
|
||||
| 5 | 06:30 | **근본 원인 발견**: getDiagnostics.lastStepIndex stale 문제 | - | ✅ |
|
||||
| 6 | 06:45 | SDK 소스 전체 분석 (antigravity-sdk v1.6.0 — EventMonitor, CascadeManager) | - | ✅ |
|
||||
| 7 | 06:55 | **PRIMARY RELAY 재작성** — rawRPC 직접 5초 폴링으로 전환 | - | 🔧 |
|
||||
|
||||
46
docs/devlog/entries/20260308-003.md
Normal file
46
docs/devlog/entries/20260308-003.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# Discord Bridge 딥 디버깅 — 시행착오 기록
|
||||
|
||||
- **시간**: 2026-03-08 05:30~07:00
|
||||
- **Vikunja**: #252 → done, #253 진행중, #251 코멘트 추가
|
||||
|
||||
## 시행착오 요약 (소거법)
|
||||
|
||||
### ❌ 시도 1: Bot 재시작 불필요
|
||||
- **가설**: Bot이 죽어서 메시지가 안 간다
|
||||
- **현실**: Bot은 PID 25508로 정상 동작 중이었음
|
||||
- **배움**: Bot 프로세스 확인은 `Get-Process -Name python | Select PID,StartTime`
|
||||
|
||||
### ❌ 시도 2: 수동 테스트 파일 깨짐 (BOM 인코딩)
|
||||
- **가설**: Bot이 파일을 안 읽는다
|
||||
- **현실**: `cmd /c echo {...} > file.json`이 BOM(FF FE) 포함 UTF-16 생성
|
||||
- **배움**: **테스트 파일은 PowerShell Set-Content -Encoding UTF8 사용**
|
||||
- **증거**: Bot 로그에 `Expecting property name enclosed in double quotes` 반복
|
||||
|
||||
### ❌ 시도 3: getDiagnostics 기반 진단 폴링 무의미
|
||||
- **가설**: getDiagnostics 데이터로 step 변화를 잡을 수 있다
|
||||
- **현실**: `getDiagnostics.recentTrajectories.lastStepIndex`가 **실시간 업데이트 안 됨**
|
||||
- **증거**: POLL#1~#2 모두 `steps=1237 known=0` 고정 (실제 step은 1239+)
|
||||
- **배움**: **getDiagnostics는 세션 메타데이터용, 실시간 step 추적 불가**
|
||||
|
||||
### ❌ 시도 4: SDK EventMonitor 의존 불가
|
||||
- **가설**: SDK monitor.onStepCountChanged가 실시간 감지
|
||||
- **현실**: EventMonitor._pollTrajectories()가 getDiagnostics 사용 → stale
|
||||
- **배움**: **SDK EventMonitor는 실시간 step 추적에 부적합**
|
||||
|
||||
### ✅ 최종 해결: rawRPC 직접 폴링
|
||||
- `GetCascadeTrajectorySteps` rawRPC는 **실시간 step 데이터를 정확히 반환**
|
||||
- 5초 간격 폴링으로 PLANNER_RESPONSE, NOTIFY_USER, TASK_BOUNDARY, WAITING 릴레이
|
||||
- `getDiagnostics`는 active session ID 확인 용도로만 (최초 + 60초마다)
|
||||
|
||||
## 핵심 교훈
|
||||
|
||||
| # | 교훈 | 카테고리 |
|
||||
|---|------|----------|
|
||||
| 1 | `cmd /c echo`로 JSON 만들지 마라 (BOM) | Windows |
|
||||
| 2 | `getDiagnostics.lastStepIndex`는 stale | SDK |
|
||||
| 3 | SDK EventMonitor는 getDiagnostics 의존 | SDK |
|
||||
| 4 | `rawRPC('GetCascadeTrajectorySteps')`만 실시간 | SDK |
|
||||
| 5 | Step control은 `vscode.commands` 사용 | SDK |
|
||||
| 6 | 분석 문서는 brain이 아닌 프로젝트 docs에 저장 | 프로세스 |
|
||||
|
||||
## 참조: `docs/discord-bridge-analysis.md`
|
||||
147
docs/discord-bridge-analysis.md
Normal file
147
docs/discord-bridge-analysis.md
Normal file
@@ -0,0 +1,147 @@
|
||||
# Discord Bridge 디버깅 분석 로그
|
||||
|
||||
> 날짜: 2026-03-08
|
||||
> 세션: e7b46728-6c7d-4220-b45a-d79e5a8c2318
|
||||
|
||||
## 1. Step Type 전체 매핑 (775 steps)
|
||||
|
||||
`GetCascadeTrajectorySteps` RPC로 현재 세션의 775개 step을 덤프한 결과:
|
||||
|
||||
| Step Type | 횟수 | Statuses | Data Key | Discord 전달 여부 |
|
||||
|-----------|------|----------|----------|------------------|
|
||||
| PLANNER_RESPONSE | 218 | DONE | plannerResponse | ✅ AI 응답 (핵심) |
|
||||
| EPHEMERAL_MESSAGE | 186 | DONE | ephemeralMessage | ❌ 내부 시스템 알림 |
|
||||
| RUN_COMMAND | 81 | DONE, CANCELED | runCommand | ✅ 명령 실행 (WAITING 시) |
|
||||
| TASK_BOUNDARY | 71 | DONE | taskBoundary | 🟡 작업 진행 상태 |
|
||||
| USER_INPUT | 38 | DONE | userInput | 🟡 사용자 입력 |
|
||||
| VIEW_FILE | 38 | DONE | viewFile, permissions | ❌ 파일 읽기 |
|
||||
| CODE_ACTION | 36 | DONE, ERROR | codeAction, error | ✅ 파일 수정/생성 (WAITING 시) |
|
||||
| ERROR_MESSAGE | 33 | DONE | errorMessage | ❌ 에러 |
|
||||
| GREP_SEARCH | 18 | DONE | grepSearch | ❌ 검색 |
|
||||
| NOTIFY_USER | 18 | DONE | notifyUser | ✅ 사용자 알림 |
|
||||
| VIEW_CODE_ITEM | 9 | DONE | viewCodeItem | ❌ 코드 조회 |
|
||||
| CONVERSATION_HISTORY | 7 | DONE | conversationHistory | ❌ 대화 이력 주입 |
|
||||
| KNOWLEDGE_ARTIFACTS | 7 | DONE | knowledgeArtifacts | ❌ KI 주입 |
|
||||
| CHECKPOINT | 7 | DONE | checkpoint | ❌ 세션 체크포인트 |
|
||||
| LIST_DIRECTORY | 4 | DONE | listDirectory, permissions | ❌ 디렉토리 조회 |
|
||||
| VIEW_FILE_OUTLINE | 2 | DONE | viewFileOutline | ❌ 파일 아웃라인 |
|
||||
| FIND | 2 | DONE | find | ❌ 파일 검색 |
|
||||
|
||||
### PLANNER_RESPONSE 구조
|
||||
```json
|
||||
{
|
||||
"thinking": "내부 사고 과정 (SKIP)",
|
||||
"response": "사용자 대면 텍스트",
|
||||
"modifiedResponse": "정리된 버전 (있으면 우선 사용)",
|
||||
"toolCalls": [{"name": "...", "argumentsJson": "..."}],
|
||||
"thinkingDuration": "0.9s",
|
||||
"stopReason": "STOP_REASON_STOP_PATTERN"
|
||||
}
|
||||
```
|
||||
|
||||
### WAITING 상태 미관측
|
||||
775 steps 중 `WAITING` 상태가 **0개**. 이유:
|
||||
1. `SafeToAutoRun=true` → WAITING 없이 바로 실행
|
||||
2. 이미 승인/거부된 step → DONE/CANCELED로 변환
|
||||
3. `GetCascadeTrajectorySteps`는 완료된 step만 반환하는 것으로 보임
|
||||
|
||||
---
|
||||
|
||||
## 2. SDK 아키텍처 분석 (antigravity-sdk v1.6.0)
|
||||
|
||||
### 전체 구조
|
||||
```
|
||||
AntigravitySDK
|
||||
├── commands: CommandBridge ← vscode.commands.executeCommand 래퍼
|
||||
├── state: StateBridge ← state.vscdb (USS) 직접 읽기
|
||||
├── cascade: CascadeManager ← 대화 관리 + step control
|
||||
├── monitor: EventMonitor ← 상태 변화 감지 (polling)
|
||||
├── ls: LSBridge ← Language Server RPC (rawRPC)
|
||||
└── integration: IntegrationManager ← Agent View UI 커스터마이즈
|
||||
```
|
||||
|
||||
### EventMonitor (transport/event-monitor.ts)
|
||||
- **USS 폴링**: `state.vscdb` 키 크기 변화 감지 (setInterval)
|
||||
- **Trajectory 폴링**: `antigravity.getDiagnostics` → `recentTrajectories[].lastStepIndex` 비교
|
||||
- 데이터 소스: `vscode.commands.executeCommand('antigravity.getDiagnostics')`
|
||||
- `recentTrajectories`는 최근 10개 대화만 포함
|
||||
|
||||
### Step Control (cascade/cascade-manager.ts)
|
||||
|
||||
| 메서드 | VS Code 명령어 | 용도 |
|
||||
|--------|----------------|------|
|
||||
| `acceptStep()` | `antigravity.agent.acceptAgentStep` | 코드 수정 승인 |
|
||||
| `rejectStep()` | `antigravity.agent.rejectAgentStep` | 코드 수정 거부 |
|
||||
| `acceptTerminalCommand()` | `antigravity.terminalCommand.accept` | 터미널 명령 승인 |
|
||||
| `rejectTerminalCommand()` | `antigravity.terminalCommand.reject` | 터미널 명령 거부 |
|
||||
| `acceptCommand()` | `antigravity.command.accept` | 비터미널 액션 승인 |
|
||||
| `rejectCommand()` | `antigravity.command.reject` | 비터미널 액션 거부 |
|
||||
|
||||
> **핵심**: Step control은 **vscode.commands**, rawRPC가 아님!
|
||||
|
||||
---
|
||||
|
||||
## 3. 파이프라인 테스트 (소거법)
|
||||
|
||||
### 파이프라인 구조
|
||||
```
|
||||
Extension step event → 텍스트 추출 → chat_snapshots/*.json 쓰기
|
||||
→ Bot scanner (5초) → Discord 전송
|
||||
```
|
||||
|
||||
### 테스트 결과
|
||||
|
||||
| Stage | 테스트 | 결과 |
|
||||
|-------|--------|------|
|
||||
| 1. Step 감지 | onStepCountChanged | ✅ step 1239 (+2) |
|
||||
| 1. 등록 | register 파일 | ✅ e7b46728→gravity_control |
|
||||
| 2. 텍스트 추출 | PLANNER_RESPONSE | ✅ 24 chars |
|
||||
| 3. 파일 쓰기 | chat_snapshots/*.json | ✅ 파일 생성됨 |
|
||||
| 4. Bot 스캔 | chat_snapshot_scanner | ✅ 정상 동작 (정상 JSON) |
|
||||
| 5. Discord 전송 | 채널 전송 | ✅ 수동 테스트 파일 도착 |
|
||||
|
||||
### 핵심 문제 발견
|
||||
|
||||
**`getDiagnostics.recentTrajectories.lastStepIndex`가 실시간 업데이트되지 않는다.**
|
||||
|
||||
Console POLL 데이터:
|
||||
```
|
||||
[POLL#1] e7b46728 steps=1237 known=0 "Debugging Discord Bridge"
|
||||
[POLL#2] e7b46728 steps=1237 known=0 "Debugging Discord Bridge"
|
||||
```
|
||||
|
||||
- `steps=1237` — getDiagnostics에서 반환하는 lastStepIndex
|
||||
- 실제로는 1239+ steps가 존재 (step event는 1239 감지)
|
||||
- 이후 대화 턴에서 step이 계속 추가되지만 `lastStepIndex`는 1237에서 변하지 않음
|
||||
- 결과: SDK EventMonitor가 변화를 감지 못함 → `onStepCountChanged` 미발생
|
||||
|
||||
### `known=0` 문제
|
||||
- POLL에서 `known=0` = `lastSeenStep` 맵이 비어있음
|
||||
- step event에서 `lastSeenStep.set()`이 실행되어야 하지만,
|
||||
one-time full dump의 async 대기 중에 POLL이 먼저 실행될 수 있음
|
||||
- MISSED STEPS 복구 조건이 `known > 0`이라 초기 상태에서 작동 안 함
|
||||
|
||||
---
|
||||
|
||||
## 4. 남은 문제 & 다음 단계
|
||||
|
||||
### 근본 원인
|
||||
`getDiagnostics`의 `lastStepIndex`가 실시간 반영되지 않아
|
||||
SDK EventMonitor의 trajectory polling이 새 step을 감지하지 못함.
|
||||
|
||||
### 적용된 해결책 (2026-03-08 06:55)
|
||||
|
||||
**PRIMARY RELAY 완전 재작성**: `getDiagnostics` 의존 제거, 직접 `rawRPC` 폴링
|
||||
|
||||
```
|
||||
setInterval (5초마다):
|
||||
1. getDiagnostics로 active session ID 확보 (초회 + 60초마다 갱신)
|
||||
2. rawRPC('GetCascadeTrajectorySteps', {cascadeId, startStepIndex}) 직접 호출
|
||||
3. step count 변화 감지 → 새 step 추출
|
||||
4. PLANNER_RESPONSE → chat_snapshots (AI 응답)
|
||||
5. NOTIFY_USER → chat_snapshots (알림)
|
||||
6. TASK_BOUNDARY → chat_snapshots (작업 상태)
|
||||
7. WAITING → pending approval (승인 대기)
|
||||
```
|
||||
|
||||
이 방식은 `getDiagnostics.lastStepIndex`의 stale 문제를 완전히 우회함.
|
||||
@@ -220,7 +220,34 @@ async function initSDK(context) {
|
||||
}
|
||||
// Track last seen step per session to avoid re-fetching
|
||||
const lastSeenStep = new Map();
|
||||
const lastSnapshotText = new Map(); // dedup: last written text per session
|
||||
const lastSnapshotText = new Map();
|
||||
const registeredSessions = new Set(); // track which sessions have been registered
|
||||
/**
|
||||
* Write a registration file for the Bot to discover session → project mapping.
|
||||
* Called automatically on first step event per session.
|
||||
*/
|
||||
function writeRegistration(sessionId) {
|
||||
if (registeredSessions.has(sessionId)) {
|
||||
return;
|
||||
}
|
||||
registeredSessions.add(sessionId);
|
||||
try {
|
||||
const regDir = path.join(bridgePath, 'register');
|
||||
if (!fs.existsSync(regDir)) {
|
||||
fs.mkdirSync(regDir, { recursive: true });
|
||||
}
|
||||
const data = {
|
||||
conversation_id: sessionId,
|
||||
project_name: projectName,
|
||||
timestamp: Date.now() / 1000,
|
||||
};
|
||||
fs.writeFileSync(path.join(regDir, `${sessionId}.json`), JSON.stringify(data, null, 2), 'utf-8');
|
||||
console.log(`Gravity Bridge: registered session ${sessionId.substring(0, 8)} → ${projectName}`);
|
||||
}
|
||||
catch (e) {
|
||||
console.log(`Gravity Bridge: registration write error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
function setupMonitor() {
|
||||
if (!sdk) {
|
||||
return;
|
||||
@@ -228,6 +255,51 @@ function setupMonitor() {
|
||||
// Step count changed → fetch new steps via GetCascadeTrajectorySteps
|
||||
sdk.monitor.onStepCountChanged(async (e) => {
|
||||
console.log(`Gravity Bridge: [SDK] step changed: "${e.title}" step ${e.newCount} (+${e.delta})`);
|
||||
// Auto-register session with Bot on first step event
|
||||
writeRegistration(e.sessionId);
|
||||
// ── ONE-TIME FULL STEP TYPE DUMP ──
|
||||
if (!lastSeenStep.has(e.sessionId)) {
|
||||
try {
|
||||
const fullData = await sdk.ls.rawRPC('GetCascadeTrajectorySteps', {
|
||||
cascadeId: e.sessionId
|
||||
});
|
||||
if (fullData && Array.isArray(fullData.steps)) {
|
||||
const typeCounts = new Map();
|
||||
for (const step of fullData.steps) {
|
||||
const t = (step.type || '').replace('CORTEX_STEP_TYPE_', '');
|
||||
const s = (step.status || '').replace('CORTEX_STEP_STATUS_', '');
|
||||
const dataKeys = Object.keys(step).filter(k => !['type', 'status', 'metadata'].includes(k));
|
||||
if (!typeCounts.has(t)) {
|
||||
typeCounts.set(t, { count: 0, statuses: new Set(), keys: new Set(), sample: step });
|
||||
}
|
||||
const entry = typeCounts.get(t);
|
||||
entry.count++;
|
||||
entry.statuses.add(s);
|
||||
for (const k of dataKeys) {
|
||||
entry.keys.add(k);
|
||||
}
|
||||
}
|
||||
console.log(`Gravity Bridge: ══════════════════════════════════════`);
|
||||
console.log(`Gravity Bridge: FULL STEP TYPE MAP (${fullData.steps.length} total steps)`);
|
||||
console.log(`Gravity Bridge: ══════════════════════════════════════`);
|
||||
for (const [type, info] of typeCounts.entries()) {
|
||||
console.log(`Gravity Bridge: [TYPE] ${type} ×${info.count} statuses=[${[...info.statuses].join(',')}] keys=[${[...info.keys].join(',')}]`);
|
||||
// Dump ONE sample of each type
|
||||
const s = info.sample;
|
||||
const dataKeys = Object.keys(s).filter(k => !['type', 'status', 'metadata'].includes(k));
|
||||
for (const k of dataKeys) {
|
||||
const v = s[k];
|
||||
const vStr = typeof v === 'object' ? JSON.stringify(v).substring(0, 150) : String(v).substring(0, 150);
|
||||
console.log(`Gravity Bridge: .${k} (${typeof v}): ${vStr}`);
|
||||
}
|
||||
}
|
||||
console.log(`Gravity Bridge: ══════════════════════════════════════`);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.log(`Gravity Bridge: full dump error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
try {
|
||||
// IMPORTANT: Only fetch NEW steps, never re-fetch history
|
||||
const fromStep = Math.max(lastSeenStep.get(e.sessionId) ?? e.newCount - e.delta, e.newCount - e.delta);
|
||||
@@ -244,32 +316,94 @@ function setupMonitor() {
|
||||
for (const step of newSteps) {
|
||||
const sType = step.type || '';
|
||||
const sStatus = step.status || '';
|
||||
// ── RUN_COMMAND + WAITING → Pending Approval ──
|
||||
if (sType.includes('RUN_COMMAND') && sStatus.includes('WAITING')) {
|
||||
const shortType = sType.replace('CORTEX_STEP_TYPE_', '');
|
||||
const shortStatus = sStatus.replace('CORTEX_STEP_STATUS_', '');
|
||||
// ── DIAGNOSTIC: log ALL step types (minimal) ──
|
||||
console.log(`Gravity Bridge: [STEP] ${shortType} ${shortStatus}`);
|
||||
// ══════════════════════════════════════════════
|
||||
// ANY WAITING step → Pending Approval to Discord
|
||||
// ══════════════════════════════════════════════
|
||||
if (sStatus.includes('WAITING')) {
|
||||
let description = '';
|
||||
let command = '';
|
||||
if (sType.includes('RUN_COMMAND')) {
|
||||
const rc = step.runCommand || {};
|
||||
const cmdLine = rc.commandLine || rc.proposedCommandLine || '';
|
||||
command = rc.commandLine || rc.proposedCommandLine || '';
|
||||
description = `💻 **명령 실행 요청**\n\`\`\`\n${command}\n\`\`\`\ncwd: ${rc.cwd || ''}`;
|
||||
}
|
||||
else if (sType.includes('EDIT_FILE') || sType.includes('CODE_EDIT') || sType.includes('CODE_ACTION') || sType.includes('WRITE_FILE') || sType.includes('FILE_EDIT')) {
|
||||
// File edit/write/code action
|
||||
const edit = step.codeEdit || step.editFile || step.writeFile || step.codeAction || {};
|
||||
const filePath = edit.filePath || edit.targetFile || edit.path || '';
|
||||
const desc = edit.description || edit.instruction || '';
|
||||
command = `📝 파일 수정: ${filePath}`;
|
||||
description = `📝 **파일 변경 확인**\n파일: \`${filePath}\`\n${desc ? `설명: ${desc}` : ''}`;
|
||||
// Full dump for diagnostic
|
||||
console.log(`Gravity Bridge: [STEP-DETAIL] ${shortType} WAITING keys=${JSON.stringify(Object.keys(step).filter(k => !['type', 'status', 'metadata'].includes(k)))}`);
|
||||
for (const k of Object.keys(step).filter(k => !['type', 'status', 'metadata'].includes(k))) {
|
||||
const v = step[k];
|
||||
console.log(`Gravity Bridge: [STEP-DETAIL] .${k} = ${typeof v === 'object' ? JSON.stringify(v).substring(0, 200) : String(v).substring(0, 200)}`);
|
||||
}
|
||||
}
|
||||
else if (sType.includes('FILE_ACCESS') || sType.includes('READ_FILE') || sType.includes('FILE_READ')) {
|
||||
// File access permission
|
||||
const fa = step.fileAccess || step.readFile || step.fileRead || {};
|
||||
const filePath = fa.filePath || fa.path || '';
|
||||
command = `📖 파일 접근: ${filePath}`;
|
||||
description = `📖 **파일 접근 권한 요청**\n파일: \`${filePath}\``;
|
||||
console.log(`Gravity Bridge: [STEP-DETAIL] ${shortType} WAITING keys=${JSON.stringify(Object.keys(step).filter(k => !['type', 'status', 'metadata'].includes(k)))}`);
|
||||
for (const k of Object.keys(step).filter(k => !['type', 'status', 'metadata'].includes(k))) {
|
||||
const v = step[k];
|
||||
console.log(`Gravity Bridge: [STEP-DETAIL] .${k} = ${typeof v === 'object' ? JSON.stringify(v).substring(0, 200) : String(v).substring(0, 200)}`);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Unknown WAITING step — still relay it with full diagnostic
|
||||
const stepKeys = Object.keys(step).filter(k => !['type', 'status', 'metadata'].includes(k));
|
||||
command = `⏳ ${shortType}`;
|
||||
description = `⏳ **대기 중: ${shortType}**\nkeys: ${stepKeys.join(', ')}`;
|
||||
console.log(`Gravity Bridge: [STEP-DETAIL] UNKNOWN WAITING: ${shortType} keys=${JSON.stringify(stepKeys)}`);
|
||||
for (const k of stepKeys) {
|
||||
const v = step[k];
|
||||
console.log(`Gravity Bridge: [STEP-DETAIL] .${k} = ${typeof v === 'object' ? JSON.stringify(v).substring(0, 200) : String(v).substring(0, 200)}`);
|
||||
}
|
||||
}
|
||||
writePendingApproval({
|
||||
conversation_id: e.sessionId,
|
||||
command: cmdLine,
|
||||
description: `💻 ${e.title}\n\`\`\`\n${cmdLine}\n\`\`\`\ncwd: ${rc.cwd || ''}`,
|
||||
command: command,
|
||||
description: `${description}\n\n🏷️ ${e.title}`,
|
||||
});
|
||||
console.log(`Gravity Bridge: [SDK] ⏳ pending: "${cmdLine.substring(0, 100)}"`);
|
||||
console.log(`Gravity Bridge: [SDK] ⏳ pending ${shortType}: "${command.substring(0, 80)}"`);
|
||||
continue;
|
||||
}
|
||||
// ── PLANNER_RESPONSE → collect AI text (COMPLETED/DONE only) ──
|
||||
// ══════════════════════════════════════════════
|
||||
// PLANNER_RESPONSE → AI text relay (COMPLETED/DONE)
|
||||
// ══════════════════════════════════════════════
|
||||
if (sType.includes('PLANNER_RESPONSE')) {
|
||||
if (!sStatus.includes('COMPLETED') && !sStatus.includes('DONE')) {
|
||||
continue;
|
||||
}
|
||||
const pr = step.plannerResponse;
|
||||
// Use confirmed field: plannerResponse.response or .modifiedResponse
|
||||
const responseText = pr?.modifiedResponse || pr?.response || '';
|
||||
if (responseText && typeof responseText === 'string' && responseText.length > 0) {
|
||||
lastPlannerText = responseText; // Overwrite — last one wins
|
||||
lastPlannerText = responseText;
|
||||
console.log(`Gravity Bridge: [SDK] 📝 planner response found (${responseText.length} chars)`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// ══════════════════════════════════════════════
|
||||
// NOTIFY_USER → also relay as chat snapshot
|
||||
// ══════════════════════════════════════════════
|
||||
if (sType.includes('NOTIFY_USER') && (sStatus.includes('COMPLETED') || sStatus.includes('DONE'))) {
|
||||
const nu = step.notifyUser;
|
||||
const content = nu?.notificationContent || '';
|
||||
if (content && content.length > 0) {
|
||||
// Write NOTIFY_USER as snapshot too
|
||||
writeChatSnapshot(`📣 **알림**\n\n${content}`);
|
||||
console.log(`Gravity Bridge: [SDK] 📣 NOTIFY_USER relayed (${content.length} chars)`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Write the LAST planner response as snapshot (with dedup)
|
||||
if (lastPlannerText && lastPlannerText !== lastSnapshotText.get(e.sessionId)) {
|
||||
@@ -289,11 +423,13 @@ function setupMonitor() {
|
||||
// New conversation started
|
||||
sdk.monitor.onNewConversation((e) => {
|
||||
console.log(`Gravity Bridge: [SDK] new conversation: ${e.title}`);
|
||||
writeRegistration(e.sessionId || e.id || '');
|
||||
writeChatSnapshot(`🚀 **${e.title}** — 새 대화 시작`);
|
||||
});
|
||||
// Active session changed
|
||||
sdk.monitor.onActiveSessionChanged((e) => {
|
||||
console.log(`Gravity Bridge: [SDK] active session: "${e.title}" (${e.sessionId?.substring(0, 8)})`);
|
||||
writeRegistration(e.sessionId || e.id || '');
|
||||
});
|
||||
// State changed (USS update)
|
||||
sdk.monitor.onStateChanged((e) => {
|
||||
@@ -302,6 +438,136 @@ function setupMonitor() {
|
||||
// Start monitoring (USS every 3s, trajectory every 2s for faster detection)
|
||||
sdk.monitor.start(3000, 2000);
|
||||
console.log('Gravity Bridge: [SDK] monitor started (USS 3s, trajectory 2s)');
|
||||
// ══════════════════════════════════════════════════════════════════════
|
||||
// PRIMARY RELAY: Direct step polling via rawRPC (getDiagnostics is stale!)
|
||||
// getDiagnostics.lastStepIndex does NOT update in real-time.
|
||||
// Instead, we poll GetCascadeTrajectorySteps directly for the active session.
|
||||
// ══════════════════════════════════════════════════════════════════════
|
||||
let pollCount = 0;
|
||||
let activeSessionId = '';
|
||||
let activeSessionTitle = '';
|
||||
let polledStepCount = 0;
|
||||
setInterval(async () => {
|
||||
pollCount++;
|
||||
try {
|
||||
// Phase 1: Discover active session (first time or periodically)
|
||||
if (!activeSessionId || pollCount % 12 === 0) {
|
||||
try {
|
||||
const raw = await vscode.commands.executeCommand('antigravity.getDiagnostics');
|
||||
if (raw && typeof raw === 'string') {
|
||||
const diag = JSON.parse(raw);
|
||||
if (Array.isArray(diag.recentTrajectories) && diag.recentTrajectories.length > 0) {
|
||||
const first = diag.recentTrajectories[0];
|
||||
if (first.googleAgentId && first.googleAgentId !== activeSessionId) {
|
||||
activeSessionId = first.googleAgentId;
|
||||
activeSessionTitle = first.summary || 'Untitled';
|
||||
polledStepCount = first.lastStepIndex || 0;
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] 🎯 active session: ${activeSessionId.substring(0, 8)} "${activeSessionTitle}" steps=${polledStepCount}`);
|
||||
writeRegistration(activeSessionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
if (pollCount <= 3) {
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] getDiag error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
if (!activeSessionId)
|
||||
return;
|
||||
}
|
||||
// Phase 2: Fetch latest steps via rawRPC (RELIABLE, not stale!)
|
||||
const stepsData = await sdk.ls.rawRPC('GetCascadeTrajectorySteps', {
|
||||
cascadeId: activeSessionId,
|
||||
startStepIndex: polledStepCount > 2 ? polledStepCount - 2 : 0
|
||||
});
|
||||
if (!stepsData || !Array.isArray(stepsData.steps)) {
|
||||
if (pollCount <= 3) {
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] no steps data`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const allSteps = stepsData.steps;
|
||||
const currentMax = allSteps.length > 0
|
||||
? Math.max(...allSteps.map((s) => s.stepIndex ?? s.index ?? 0), allSteps.length)
|
||||
: polledStepCount;
|
||||
if (currentMax <= polledStepCount) {
|
||||
// No new steps — log every 12th poll
|
||||
if (pollCount % 12 === 0) {
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] no change: ${activeSessionId.substring(0, 8)} steps=${currentMax}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Phase 3: New steps detected! Process them.
|
||||
const delta = currentMax - polledStepCount;
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] 🆕 +${delta} steps (${polledStepCount}→${currentMax}) "${activeSessionTitle}"`);
|
||||
const newSteps = allSteps.slice(-delta);
|
||||
polledStepCount = currentMax;
|
||||
let lastPlannerText = '';
|
||||
for (const step of newSteps) {
|
||||
const sType = String(step.type || '');
|
||||
const sStatus = String(step.status || '');
|
||||
// PLANNER_RESPONSE → AI text (main content)
|
||||
if (sType.includes('PLANNER_RESPONSE') && (sStatus.includes('DONE') || sStatus.includes('COMPLETED'))) {
|
||||
const pr = step.plannerResponse;
|
||||
const text = pr?.modifiedResponse || pr?.response || '';
|
||||
if (text && text.length > 0) {
|
||||
lastPlannerText = text;
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] 📝 planner ${text.length} chars`);
|
||||
}
|
||||
}
|
||||
// NOTIFY_USER → user notification
|
||||
if (sType.includes('NOTIFY_USER') && (sStatus.includes('DONE') || sStatus.includes('COMPLETED'))) {
|
||||
const nu = step.notifyUser;
|
||||
const content = nu?.notificationContent || '';
|
||||
if (content && content.length > 0) {
|
||||
writeChatSnapshot(`📣 **알림**\n\n${content}`);
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] 📣 notify ${content.length} chars`);
|
||||
}
|
||||
}
|
||||
// TASK_BOUNDARY → task status update
|
||||
if (sType.includes('TASK_BOUNDARY') && (sStatus.includes('DONE') || sStatus.includes('COMPLETED'))) {
|
||||
const tb = step.taskBoundary;
|
||||
if (tb?.taskName) {
|
||||
writeChatSnapshot(`📋 **작업**: ${tb.taskName}\n상태: ${tb.taskStatus || ''}\n${tb.taskSummary || ''}`);
|
||||
}
|
||||
}
|
||||
// WAITING steps → pending approval (any type)
|
||||
if (sStatus.includes('WAITING')) {
|
||||
const shortType = sType.replace(/CORTEX_STEP_TYPE_/g, '');
|
||||
let command = `⏳ ${shortType}`;
|
||||
let description = `⏳ **대기 중**: ${shortType}`;
|
||||
if (sType.includes('RUN_COMMAND')) {
|
||||
const cmd = step.runCommand?.commandLine || '';
|
||||
command = `▶️ ${cmd.substring(0, 80)}`;
|
||||
description = `▶️ **명령 실행 확인**\n\`\`\`\n${cmd}\n\`\`\``;
|
||||
}
|
||||
else if (sType.includes('CODE_ACTION') || sType.includes('WRITE')) {
|
||||
const file = step.codeAction?.filePath || step.writeToFile?.filePath || '';
|
||||
command = `✏️ 파일 수정: ${file}`;
|
||||
description = `✏️ **파일 수정 확인**\n파일: \`${file}\``;
|
||||
}
|
||||
writePendingApproval({
|
||||
conversation_id: activeSessionId,
|
||||
command: command,
|
||||
description: description,
|
||||
});
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] ⏳ ${shortType} WAITING`);
|
||||
}
|
||||
}
|
||||
// Write latest planner response as snapshot (dedup)
|
||||
if (lastPlannerText && lastPlannerText !== lastSnapshotText.get(activeSessionId)) {
|
||||
lastSnapshotText.set(activeSessionId, lastPlannerText);
|
||||
writeChatSnapshot(`🤖 **${activeSessionTitle}**\n\n${lastPlannerText}`);
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] 💬 snapshot ${lastPlannerText.length} chars`);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
if (pollCount <= 5 || pollCount % 12 === 0) {
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
// ─── Response Watcher (Discord approval → Antigravity RPC) ───
|
||||
let responseWatcher = null;
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -193,7 +193,30 @@ async function initSDK(context: vscode.ExtensionContext): Promise<boolean> {
|
||||
|
||||
// Track last seen step per session to avoid re-fetching
|
||||
const lastSeenStep = new Map<string, number>();
|
||||
const lastSnapshotText = new Map<string, string>(); // dedup: last written text per session
|
||||
const lastSnapshotText = new Map<string, string>();
|
||||
const registeredSessions = new Set<string>(); // track which sessions have been registered
|
||||
|
||||
/**
|
||||
* Write a registration file for the Bot to discover session → project mapping.
|
||||
* Called automatically on first step event per session.
|
||||
*/
|
||||
function writeRegistration(sessionId: string) {
|
||||
if (registeredSessions.has(sessionId)) { return; }
|
||||
registeredSessions.add(sessionId);
|
||||
try {
|
||||
const regDir = path.join(bridgePath, 'register');
|
||||
if (!fs.existsSync(regDir)) { fs.mkdirSync(regDir, { recursive: true }); }
|
||||
const data = {
|
||||
conversation_id: sessionId,
|
||||
project_name: projectName,
|
||||
timestamp: Date.now() / 1000,
|
||||
};
|
||||
fs.writeFileSync(path.join(regDir, `${sessionId}.json`), JSON.stringify(data, null, 2), 'utf-8');
|
||||
console.log(`Gravity Bridge: registered session ${sessionId.substring(0, 8)} → ${projectName}`);
|
||||
} catch (e: any) {
|
||||
console.log(`Gravity Bridge: registration write error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function setupMonitor() {
|
||||
if (!sdk) { return; }
|
||||
@@ -202,6 +225,50 @@ function setupMonitor() {
|
||||
sdk.monitor.onStepCountChanged(async (e: any) => {
|
||||
console.log(`Gravity Bridge: [SDK] step changed: "${e.title}" step ${e.newCount} (+${e.delta})`);
|
||||
|
||||
// Auto-register session with Bot on first step event
|
||||
writeRegistration(e.sessionId);
|
||||
|
||||
// ── ONE-TIME FULL STEP TYPE DUMP ──
|
||||
if (!lastSeenStep.has(e.sessionId)) {
|
||||
try {
|
||||
const fullData = await sdk.ls.rawRPC('GetCascadeTrajectorySteps', {
|
||||
cascadeId: e.sessionId
|
||||
});
|
||||
if (fullData && Array.isArray(fullData.steps)) {
|
||||
const typeCounts = new Map<string, { count: number, statuses: Set<string>, keys: Set<string>, sample: any }>();
|
||||
for (const step of fullData.steps) {
|
||||
const t = (step.type || '').replace('CORTEX_STEP_TYPE_', '');
|
||||
const s = (step.status || '').replace('CORTEX_STEP_STATUS_', '');
|
||||
const dataKeys = Object.keys(step).filter(k => !['type', 'status', 'metadata'].includes(k));
|
||||
if (!typeCounts.has(t)) {
|
||||
typeCounts.set(t, { count: 0, statuses: new Set(), keys: new Set(), sample: step });
|
||||
}
|
||||
const entry = typeCounts.get(t)!;
|
||||
entry.count++;
|
||||
entry.statuses.add(s);
|
||||
for (const k of dataKeys) { entry.keys.add(k); }
|
||||
}
|
||||
|
||||
console.log(`Gravity Bridge: ══════════════════════════════════════`);
|
||||
console.log(`Gravity Bridge: FULL STEP TYPE MAP (${fullData.steps.length} total steps)`);
|
||||
console.log(`Gravity Bridge: ══════════════════════════════════════`);
|
||||
for (const [type, info] of typeCounts.entries()) {
|
||||
console.log(`Gravity Bridge: [TYPE] ${type} ×${info.count} statuses=[${[...info.statuses].join(',')}] keys=[${[...info.keys].join(',')}]`);
|
||||
// Dump ONE sample of each type
|
||||
const s = info.sample;
|
||||
const dataKeys = Object.keys(s).filter(k => !['type', 'status', 'metadata'].includes(k));
|
||||
for (const k of dataKeys) {
|
||||
const v = s[k];
|
||||
const vStr = typeof v === 'object' ? JSON.stringify(v).substring(0, 150) : String(v).substring(0, 150);
|
||||
console.log(`Gravity Bridge: .${k} (${typeof v}): ${vStr}`);
|
||||
}
|
||||
}
|
||||
console.log(`Gravity Bridge: ══════════════════════════════════════`);
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.log(`Gravity Bridge: full dump error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
try {
|
||||
// IMPORTANT: Only fetch NEW steps, never re-fetch history
|
||||
const fromStep = Math.max(
|
||||
@@ -223,34 +290,98 @@ function setupMonitor() {
|
||||
for (const step of newSteps) {
|
||||
const sType = step.type || '';
|
||||
const sStatus = step.status || '';
|
||||
const shortType = sType.replace('CORTEX_STEP_TYPE_', '');
|
||||
const shortStatus = sStatus.replace('CORTEX_STEP_STATUS_', '');
|
||||
|
||||
// ── RUN_COMMAND + WAITING → Pending Approval ──
|
||||
if (sType.includes('RUN_COMMAND') && sStatus.includes('WAITING')) {
|
||||
// ── DIAGNOSTIC: log ALL step types (minimal) ──
|
||||
console.log(`Gravity Bridge: [STEP] ${shortType} ${shortStatus}`);
|
||||
|
||||
// ══════════════════════════════════════════════
|
||||
// ANY WAITING step → Pending Approval to Discord
|
||||
// ══════════════════════════════════════════════
|
||||
if (sStatus.includes('WAITING')) {
|
||||
let description = '';
|
||||
let command = '';
|
||||
|
||||
if (sType.includes('RUN_COMMAND')) {
|
||||
const rc = step.runCommand || {};
|
||||
const cmdLine = rc.commandLine || rc.proposedCommandLine || '';
|
||||
writePendingApproval({
|
||||
conversation_id: e.sessionId,
|
||||
command: cmdLine,
|
||||
description: `💻 ${e.title}\n\`\`\`\n${cmdLine}\n\`\`\`\ncwd: ${rc.cwd || ''}`,
|
||||
});
|
||||
console.log(`Gravity Bridge: [SDK] ⏳ pending: "${cmdLine.substring(0, 100)}"`);
|
||||
continue;
|
||||
command = rc.commandLine || rc.proposedCommandLine || '';
|
||||
description = `💻 **명령 실행 요청**\n\`\`\`\n${command}\n\`\`\`\ncwd: ${rc.cwd || ''}`;
|
||||
|
||||
} else if (sType.includes('EDIT_FILE') || sType.includes('CODE_EDIT') || sType.includes('CODE_ACTION') || sType.includes('WRITE_FILE') || sType.includes('FILE_EDIT')) {
|
||||
// File edit/write/code action
|
||||
const edit = step.codeEdit || step.editFile || step.writeFile || step.codeAction || {};
|
||||
const filePath = edit.filePath || edit.targetFile || edit.path || '';
|
||||
const desc = edit.description || edit.instruction || '';
|
||||
command = `📝 파일 수정: ${filePath}`;
|
||||
description = `📝 **파일 변경 확인**\n파일: \`${filePath}\`\n${desc ? `설명: ${desc}` : ''}`;
|
||||
// Full dump for diagnostic
|
||||
console.log(`Gravity Bridge: [STEP-DETAIL] ${shortType} WAITING keys=${JSON.stringify(Object.keys(step).filter(k => !['type', 'status', 'metadata'].includes(k)))}`);
|
||||
for (const k of Object.keys(step).filter(k => !['type', 'status', 'metadata'].includes(k))) {
|
||||
const v = step[k];
|
||||
console.log(`Gravity Bridge: [STEP-DETAIL] .${k} = ${typeof v === 'object' ? JSON.stringify(v).substring(0, 200) : String(v).substring(0, 200)}`);
|
||||
}
|
||||
|
||||
// ── PLANNER_RESPONSE → collect AI text (COMPLETED/DONE only) ──
|
||||
} else if (sType.includes('FILE_ACCESS') || sType.includes('READ_FILE') || sType.includes('FILE_READ')) {
|
||||
// File access permission
|
||||
const fa = step.fileAccess || step.readFile || step.fileRead || {};
|
||||
const filePath = fa.filePath || fa.path || '';
|
||||
command = `📖 파일 접근: ${filePath}`;
|
||||
description = `📖 **파일 접근 권한 요청**\n파일: \`${filePath}\``;
|
||||
console.log(`Gravity Bridge: [STEP-DETAIL] ${shortType} WAITING keys=${JSON.stringify(Object.keys(step).filter(k => !['type', 'status', 'metadata'].includes(k)))}`);
|
||||
for (const k of Object.keys(step).filter(k => !['type', 'status', 'metadata'].includes(k))) {
|
||||
const v = step[k];
|
||||
console.log(`Gravity Bridge: [STEP-DETAIL] .${k} = ${typeof v === 'object' ? JSON.stringify(v).substring(0, 200) : String(v).substring(0, 200)}`);
|
||||
}
|
||||
|
||||
} else {
|
||||
// Unknown WAITING step — still relay it with full diagnostic
|
||||
const stepKeys = Object.keys(step).filter(k => !['type', 'status', 'metadata'].includes(k));
|
||||
command = `⏳ ${shortType}`;
|
||||
description = `⏳ **대기 중: ${shortType}**\nkeys: ${stepKeys.join(', ')}`;
|
||||
console.log(`Gravity Bridge: [STEP-DETAIL] UNKNOWN WAITING: ${shortType} keys=${JSON.stringify(stepKeys)}`);
|
||||
for (const k of stepKeys) {
|
||||
const v = step[k];
|
||||
console.log(`Gravity Bridge: [STEP-DETAIL] .${k} = ${typeof v === 'object' ? JSON.stringify(v).substring(0, 200) : String(v).substring(0, 200)}`);
|
||||
}
|
||||
}
|
||||
|
||||
writePendingApproval({
|
||||
conversation_id: e.sessionId,
|
||||
command: command,
|
||||
description: `${description}\n\n🏷️ ${e.title}`,
|
||||
});
|
||||
console.log(`Gravity Bridge: [SDK] ⏳ pending ${shortType}: "${command.substring(0, 80)}"`);
|
||||
continue;
|
||||
}
|
||||
// ══════════════════════════════════════════════
|
||||
// PLANNER_RESPONSE → AI text relay (COMPLETED/DONE)
|
||||
// ══════════════════════════════════════════════
|
||||
if (sType.includes('PLANNER_RESPONSE')) {
|
||||
if (!sStatus.includes('COMPLETED') && !sStatus.includes('DONE')) {
|
||||
continue;
|
||||
}
|
||||
const pr = step.plannerResponse;
|
||||
// Use confirmed field: plannerResponse.response or .modifiedResponse
|
||||
const responseText = pr?.modifiedResponse || pr?.response || '';
|
||||
if (responseText && typeof responseText === 'string' && responseText.length > 0) {
|
||||
lastPlannerText = responseText; // Overwrite — last one wins
|
||||
lastPlannerText = responseText;
|
||||
console.log(`Gravity Bridge: [SDK] 📝 planner response found (${responseText.length} chars)`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// ══════════════════════════════════════════════
|
||||
// NOTIFY_USER → also relay as chat snapshot
|
||||
// ══════════════════════════════════════════════
|
||||
if (sType.includes('NOTIFY_USER') && (sStatus.includes('COMPLETED') || sStatus.includes('DONE'))) {
|
||||
const nu = step.notifyUser;
|
||||
const content = nu?.notificationContent || '';
|
||||
if (content && content.length > 0) {
|
||||
// Write NOTIFY_USER as snapshot too
|
||||
writeChatSnapshot(`📣 **알림**\n\n${content}`);
|
||||
console.log(`Gravity Bridge: [SDK] 📣 NOTIFY_USER relayed (${content.length} chars)`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Write the LAST planner response as snapshot (with dedup)
|
||||
@@ -271,12 +402,14 @@ function setupMonitor() {
|
||||
// New conversation started
|
||||
sdk.monitor.onNewConversation((e: any) => {
|
||||
console.log(`Gravity Bridge: [SDK] new conversation: ${e.title}`);
|
||||
writeRegistration(e.sessionId || e.id || '');
|
||||
writeChatSnapshot(`🚀 **${e.title}** — 새 대화 시작`);
|
||||
});
|
||||
|
||||
// Active session changed
|
||||
sdk.monitor.onActiveSessionChanged((e: any) => {
|
||||
console.log(`Gravity Bridge: [SDK] active session: "${e.title}" (${e.sessionId?.substring(0, 8)})`);
|
||||
writeRegistration(e.sessionId || e.id || '');
|
||||
});
|
||||
|
||||
// State changed (USS update)
|
||||
@@ -287,6 +420,143 @@ function setupMonitor() {
|
||||
// Start monitoring (USS every 3s, trajectory every 2s for faster detection)
|
||||
sdk.monitor.start(3000, 2000);
|
||||
console.log('Gravity Bridge: [SDK] monitor started (USS 3s, trajectory 2s)');
|
||||
|
||||
// ══════════════════════════════════════════════════════════════════════
|
||||
// PRIMARY RELAY: Direct step polling via rawRPC (getDiagnostics is stale!)
|
||||
// getDiagnostics.lastStepIndex does NOT update in real-time.
|
||||
// Instead, we poll GetCascadeTrajectorySteps directly for the active session.
|
||||
// ══════════════════════════════════════════════════════════════════════
|
||||
let pollCount = 0;
|
||||
let activeSessionId = '';
|
||||
let activeSessionTitle = '';
|
||||
let polledStepCount = 0;
|
||||
|
||||
setInterval(async () => {
|
||||
pollCount++;
|
||||
try {
|
||||
// Phase 1: Discover active session (first time or periodically)
|
||||
if (!activeSessionId || pollCount % 12 === 0) {
|
||||
try {
|
||||
const raw = await vscode.commands.executeCommand<string>('antigravity.getDiagnostics');
|
||||
if (raw && typeof raw === 'string') {
|
||||
const diag = JSON.parse(raw);
|
||||
if (Array.isArray(diag.recentTrajectories) && diag.recentTrajectories.length > 0) {
|
||||
const first = diag.recentTrajectories[0];
|
||||
if (first.googleAgentId && first.googleAgentId !== activeSessionId) {
|
||||
activeSessionId = first.googleAgentId;
|
||||
activeSessionTitle = first.summary || 'Untitled';
|
||||
polledStepCount = first.lastStepIndex || 0;
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] 🎯 active session: ${activeSessionId.substring(0, 8)} "${activeSessionTitle}" steps=${polledStepCount}`);
|
||||
writeRegistration(activeSessionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (pollCount <= 3) { console.log(`Gravity Bridge: [POLL#${pollCount}] getDiag error: ${e.message}`); }
|
||||
}
|
||||
if (!activeSessionId) return;
|
||||
}
|
||||
|
||||
// Phase 2: Fetch latest steps via rawRPC (RELIABLE, not stale!)
|
||||
const stepsData = await sdk.ls.rawRPC('GetCascadeTrajectorySteps', {
|
||||
cascadeId: activeSessionId,
|
||||
startStepIndex: polledStepCount > 2 ? polledStepCount - 2 : 0
|
||||
});
|
||||
|
||||
if (!stepsData || !Array.isArray(stepsData.steps)) {
|
||||
if (pollCount <= 3) { console.log(`Gravity Bridge: [POLL#${pollCount}] no steps data`); }
|
||||
return;
|
||||
}
|
||||
|
||||
const allSteps = stepsData.steps;
|
||||
const currentMax = allSteps.length > 0
|
||||
? Math.max(...allSteps.map((s: any) => s.stepIndex ?? s.index ?? 0), allSteps.length)
|
||||
: polledStepCount;
|
||||
|
||||
if (currentMax <= polledStepCount) {
|
||||
// No new steps — log every 12th poll
|
||||
if (pollCount % 12 === 0) {
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] no change: ${activeSessionId.substring(0, 8)} steps=${currentMax}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Phase 3: New steps detected! Process them.
|
||||
const delta = currentMax - polledStepCount;
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] 🆕 +${delta} steps (${polledStepCount}→${currentMax}) "${activeSessionTitle}"`);
|
||||
const newSteps = allSteps.slice(-delta);
|
||||
polledStepCount = currentMax;
|
||||
|
||||
let lastPlannerText = '';
|
||||
for (const step of newSteps) {
|
||||
const sType = String(step.type || '');
|
||||
const sStatus = String(step.status || '');
|
||||
|
||||
// PLANNER_RESPONSE → AI text (main content)
|
||||
if (sType.includes('PLANNER_RESPONSE') && (sStatus.includes('DONE') || sStatus.includes('COMPLETED'))) {
|
||||
const pr = step.plannerResponse;
|
||||
const text = pr?.modifiedResponse || pr?.response || '';
|
||||
if (text && text.length > 0) {
|
||||
lastPlannerText = text;
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] 📝 planner ${text.length} chars`);
|
||||
}
|
||||
}
|
||||
|
||||
// NOTIFY_USER → user notification
|
||||
if (sType.includes('NOTIFY_USER') && (sStatus.includes('DONE') || sStatus.includes('COMPLETED'))) {
|
||||
const nu = step.notifyUser;
|
||||
const content = nu?.notificationContent || '';
|
||||
if (content && content.length > 0) {
|
||||
writeChatSnapshot(`📣 **알림**\n\n${content}`);
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] 📣 notify ${content.length} chars`);
|
||||
}
|
||||
}
|
||||
|
||||
// TASK_BOUNDARY → task status update
|
||||
if (sType.includes('TASK_BOUNDARY') && (sStatus.includes('DONE') || sStatus.includes('COMPLETED'))) {
|
||||
const tb = step.taskBoundary;
|
||||
if (tb?.taskName) {
|
||||
writeChatSnapshot(`📋 **작업**: ${tb.taskName}\n상태: ${tb.taskStatus || ''}\n${tb.taskSummary || ''}`);
|
||||
}
|
||||
}
|
||||
|
||||
// WAITING steps → pending approval (any type)
|
||||
if (sStatus.includes('WAITING')) {
|
||||
const shortType = sType.replace(/CORTEX_STEP_TYPE_/g, '');
|
||||
let command = `⏳ ${shortType}`;
|
||||
let description = `⏳ **대기 중**: ${shortType}`;
|
||||
|
||||
if (sType.includes('RUN_COMMAND')) {
|
||||
const cmd = step.runCommand?.commandLine || '';
|
||||
command = `▶️ ${cmd.substring(0, 80)}`;
|
||||
description = `▶️ **명령 실행 확인**\n\`\`\`\n${cmd}\n\`\`\``;
|
||||
} else if (sType.includes('CODE_ACTION') || sType.includes('WRITE')) {
|
||||
const file = step.codeAction?.filePath || step.writeToFile?.filePath || '';
|
||||
command = `✏️ 파일 수정: ${file}`;
|
||||
description = `✏️ **파일 수정 확인**\n파일: \`${file}\``;
|
||||
}
|
||||
|
||||
writePendingApproval({
|
||||
conversation_id: activeSessionId,
|
||||
command: command,
|
||||
description: description,
|
||||
});
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] ⏳ ${shortType} WAITING`);
|
||||
}
|
||||
}
|
||||
|
||||
// Write latest planner response as snapshot (dedup)
|
||||
if (lastPlannerText && lastPlannerText !== lastSnapshotText.get(activeSessionId)) {
|
||||
lastSnapshotText.set(activeSessionId, lastPlannerText);
|
||||
writeChatSnapshot(`🤖 **${activeSessionTitle}**\n\n${lastPlannerText}`);
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] 💬 snapshot ${lastPlannerText.length} chars`);
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (pollCount <= 5 || pollCount % 12 === 0) {
|
||||
console.log(`Gravity Bridge: [POLL#${pollCount}] error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
// ─── Response Watcher (Discord approval → Antigravity RPC) ───
|
||||
|
||||
Reference in New Issue
Block a user